Building AS/400 Internet-Based Applications with Java
Bob Maatta, Markus Abegglen, Craig Pelkie, Brian Skaarup, Daniel Stucki
International Technical Support Organization
http://www.redbooks.ibm.com
SG24-5337-00
International Technical Support Organization SG24-5337-00
Building AS/400 Internet-Based Applications with Java
January 1999 Take Note! Before using this information and the product it supports, be sure to read the general information in Appendix C, “Special Notices” on page 303.
First Edition (January 1999)
This edition applies to Version 3 Release 2 and later of OS/400
Comments may be addressed to: IBM Corporation, International Technical Support Organization Dept. JLU Building 107-2 3605 Highway 52N Rochester, Minnesota 55901-7829
When you send information to IBM, you grant IBM a non-exclusive right to use or distribute the information in any way it believes appropriate without incurring any obligation to you.
© Copyright International Business Machines Corporation 1999. All rights reserved Note to U.S Government Users - Documentation related to restricted rights - Use, duplication or disclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp. Contents
Figures ...... vii
Tables ...... xiii
Preface ...... xv The Team That Wrote This Redbook ...... xv Comments Welcome ...... xvi
Chapter 1. AS/400 Internet Application Development Overview ...... 1 1.1 From Server to Browser and Back—Fundamental Concepts ...... 1 1.1.1 The Requesting Web Page ...... 2 1.1.2 The Web Serving Application ...... 2 1.2 AS/400 Internet Application Development Techniques ...... 5 1.2.1 Other Approaches for Internet Applications ...... 5 1.2.2 Four Tools for Internet Development on the AS/400 System ...... 6 1.3 Net.Data ...... 6 1.3.1 Why Use Net.Data...... 7 1.3.2 Net.Data Processing ...... 7 1.3.3 How Net.Data Macros are Invoked ...... 9 1.3.4 A Sample Net.Data Macro...... 10 1.3.5 Source Code for the Net.Data Sample Macro ...... 12 1.3.6 When to Use Net.Data ...... 14 1.4 Common Gateway Interface (CGI) Programming ...... 15 1.4.1 Why Use CGI Programming ...... 15 1.4.2 CGI Processing ...... 16 1.4.3 APIs Used for CGI Programming...... 17 1.4.4 A Sample RPG-CGI Program ...... 20 1.4.5 Source Code for the CG_PARTS CGI Program ...... 21 1.4.6 Summary of the CGI Sample Program ...... 28 1.4.7 When to Use CGI Programs ...... 28 1.5 Java Applets ...... 28 1.5.1 The Scripting Alternative ...... 29 1.5.2 How Applets are Different from Scripting...... 30 1.5.3 Applet Processing ...... 31 1.5.4 How Applets are Different from Net.Data and CGI Programs...... 32 1.5.5 A Sample Applet ...... 32 1.5.6 When to Use Applets...... 34 1.5.7 Applet Development ...... 34 1.6 Java Servlets ...... 34 1.6.1 Why Use Servlets ...... 34 1.6.2 Servlet Processing ...... 35 1.6.3 A Sample Servlet ...... 37 1.6.4 When to Use Servlets ...... 39 1.6.5 Servlet Development ...... 40
Chapter 2. IBM HTTP Server for AS/400 ...... 41 2.1 Product Packaging ...... 41 2.2 HTTP 1.1 Protocol ...... 42 2.2.1 Persistent Connections ...... 42 2.2.2 Virtual Hosts ...... 43 2.3 Proxy, Cache, and Local Memory Cache ...... 43
© Copyright IBM Corp. 1999 iii 2.3.1 Proxy Caching ...... 43 2.3.2 Proxy Logging ...... 44 2.3.3 Local Memory Cache ...... 44 2.4 CGI Programming ...... 44 2.4.1 Java and REXX CGI ...... 44 2.4.2 Non-parsed Headers CGI ...... 45 2.4.3 QzhbCgiParse API...... 45 2.5 Persistent CGI ...... 45 2.5.1 How Persistent CGI Works ...... 46 2.5.2 Controlling Persistent CGI ...... 47 2.6 Cryptographic Support, Certificates, and Digital ID ...... 47 2.6.1 Cryptographic Access Provider ...... 47 2.6.2 Digital Certificate Manager...... 47 2.6.3 Digital ID ...... 48 2.7 WebSphere Application Server for AS/400 ...... 48 2.7.1 What WebSphere Provides ...... 48 2.7.2 Accessing the WebSphere Server ...... 48 2.8 Summary ...... 49
Chapter 3. Introduction to AS/400 Applets...... 51 3.1 The PartsView Applet ...... 51 3.1.1 Importing the Source Code for the Applet to the Workbench ...... 52 3.1.2 Resolving Problems in the Imported Applet ...... 57 3.1.3 Overview of Classes Used in the PartsView Applet ...... 61 3.1.4 Working with the Applet in the Visual Composition Editor ...... 62 3.1.5 Testing the Applet in the VisualAge for Java Applet Viewer ...... 69 3.2 Detailed Review of Java Classes Used in the Applet ...... 79 3.2.1 Design of the Applet ...... 79 3.2.2 Testing and Debugging Features in the PartsView Applet ...... 80 3.2.3 The PartsView Class ...... 81 3.2.4 The DataAccessor Interface...... 89 3.2.5 The JDBCPartsCatalog Class ...... 90 3.2.6 The TestPart Class ...... 94 3.2.7 The Part Class...... 96 3.2.8 The PartsCatalog Class ...... 100 3.3 Running the Applet in a Browser ...... 105 3.3.1 Test Environment...... 105 3.3.2 Serving the Applet from the PC Drive...... 106 3.3.3 Creating a Signed Cabinet File for Microsoft Internet Explorer 4.01 114 3.3.4 Using the CLASSPATH Environment Variable ...... 125 3.3.5 Considerations for Using CLASSPATH ...... 128 3.3.6 Serving Applets from the HTTP Server for AS/400...... 129 3.4 Working with the Sun Java Plug-in ...... 133 3.4.1 Java Plug-in Basics ...... 133 3.4.2 Working with the Java Plug-in—A Step-by-Step Approach...... 134 3.4.3 Summary of the Java Plug-in ...... 156 3.5 Conclusion ...... 156
Chapter 4. Introduction to AS/400 Servlets ...... 159 4.1 Introduction to the Servlet Support ...... 160 4.1.1 Why Use Servlets ...... 161 4.1.2 Servlets versus CGI.BIN ...... 162 4.2 How to Use Servlets ...... 163
iv Building AS/400 Internet-Based Applications with Java 4.2.1 Communication with an HTTP Server ...... 164 4.2.2 Invoking a Servlet ...... 165 4.3 A Simple Servlet ...... 165 4.4 Developing the Servlet Application ...... 166 4.5 Migrating the Applet to a Servlet ...... 169 4.5.1 Enhancing the Servlet ...... 172 4.6 Executing the Servlet ...... 174 4.6.1 Running under the Domino Go Webserver ...... 175 4.6.2 Running under the IBM HTTP Server for AS/400...... 177 4.6.3 Running Servlets on the AS/400 System ...... 177 4.6.4 Running the PartsServlet Servlet on the AS/400 System...... 178
Chapter 5. Overview of the Order Entry Application...... 179 5.1 Overview of the Order Entry Application ...... 179 5.1.1 The ABC Company ...... 179 5.1.2 The ABC Company Database ...... 179 5.1.3 A Customer Transaction ...... 180 5.1.4 Application Flow ...... 180 5.1.5 Customer Transaction Flow...... 181 5.1.6 Database Table Structure ...... 188 5.1.7 Order Entry Application Database Layout ...... 188 5.1.8 Database Terminology ...... 191
Chapter 6. Developing AS/400 Java Applets ...... 193 6.1 Shopping Application User Interface ...... 193 6.2 Shopping Application Objects and Classes ...... 196 6.3 The SelectedItems Class ...... 198 6.3.1 Writing the Class ...... 199 6.3.2 Writing the Methods ...... 199 6.4 The ItemsDb Class ...... 200 6.4.1 Common Methods All Applets Use ...... 202 6.4.2 Methods Used by the Toolbox Applet ...... 204 6.4.3 Methods Used by CartApplet...... 206 6.4.4 Methods Used by the StatusApplet ...... 208 6.5 The Toolbox Applet...... 209 6.5.1 The addAllRows Method ...... 210 6.5.2 The getSelectedIndexes Method ...... 210 6.5.3 Checking the Connections...... 210 6.6 The Cart Applet...... 211 6.6.1 Writing the Class ...... 212 6.6.2 Viewing the Methods ...... 212 6.7 The Order Status Applet ...... 215 6.8 Testing the Applets ...... 217 6.9 Serving the Applets from the AS/400 System ...... 219
Chapter 7. Developing AS/400 Java Servlets ...... 221 7.1 Running the Application ...... 222 7.2 Application Programs ...... 234 7.2.1 How the Application Works ...... 235 7.3 The Java Application Programs...... 242 7.3.1 System Performance Servlet ...... 242 7.3.2 Database Query ...... 243 7.4 Running the Application ...... 257 7.4.1 Domino Go Webserver ...... 257
v 7.4.2 IBM HTTP Server for AS/400 ...... 259
Chapter 8. Security Considerations ...... 261 8.1 Internet Security Elements...... 261 8.1.1 Transaction Security and Secure Sockets Layer ...... 262 8.1.2 HTTP Server Over SSL (HTTPS)...... 265 8.2 Digital Certificates and Certificate Authority ...... 267 8.3 AS/400 Implementation of Digital Certificate Management...... 268 8.3.1 Configuring a Digital Certificate Environment ...... 269 8.4 Creating a Self-Signed Certificate ...... 269 8.4.1 Creating an Intranet Certificate Authority ...... 270 8.4.2 Creating a Server Certificate with Your Intranet CA ...... 272 8.4.3 Configuring the Web Server to Use SSL with Server Authentication 275 8.5 Requesting a Server Certificate from an Internet CA ...... 277 8.5.1 Requesting a Server Certificate from an Internet CA ...... 278 8.5.2 Receiving a Server Certificate for this Server...... 280 8.5.3 Configuring the HTTP Server to Use SSL ...... 281 8.6 Applying Security to the Applications ...... 281 8.6.1 Servlets ...... 281 8.6.2 Additional Resources ...... 285
Chapter 9. HTTP Server Configuration...... 287 9.1 Domino Go Webserver ...... 287 9.2 ServletExpress ...... 289 9.3 IBM HTTP Server for AS/400...... 293 9.4 IBM WebSphere Application Server for AS/400 ...... 296
Appendix A. Example Programs ...... 299 A.1 Downloading the Files from the Internet Web Site...... 299 A.2 Setting up VisualAge for Java ...... 299 A.2.1 The AS/400 Toolbox for Java Classes...... 300 A.2.2 IBM Enterprise Data Access Libraries ...... 300 A.2.3 Sun JSDK Class Libraries ...... 300 A.2.4 Netscape Security ...... 300
Appendix B. IBM HTTP Server for AS400 Configuration ...... 301
Appendix C. Special Notices ...... 303
Appendix D. Related Publications ...... 305 D.1 International Technical Support Organization Publications ...... 305 D.2 Redbooks on CD-ROMs ...... 305 D.3 Other Publications ...... 305
How to Get ITSO Redbooks ...... 307 How IBM Employees Can Get ITSO Redbooks ...... 307 How Customers Can Get ITSO Redbooks ...... 308 IBM Redbook Order Form ...... 309
List of Abbreviations ...... 311
Index ...... 313
ITSO Redbook Evaluation ...... 317
vi Building AS/400 Internet-Based Applications with Java Figures
1. How an HTTP Server Processes a Request for a Dynamic Web Page...... 2 2. Form Data in HTTP Encoded Format ...... 3 3. How Net.Data Processes a Macro and Generates a Response ...... 8 4. Prompting Page Displayed by the Net.Data Macro ...... 11 5. Parts File Listing Generated by the Net.Data Macro ...... 11 6. How CGI Processing Works...... 16 7. HTML Code Used to Display the Prompting Page for the CGI Program . . . . . 21 8. Applet Processing ...... 31 9. PartsView Applet Running in the Netscape Browser ...... 33 10. Java Security Message Displayed under Netscape...... 33 11. Servlet Processing ...... 36 12. Servlet Example Prompting Page ...... 38 13. Servlet Example Output ...... 39 14. PartsView Applet ...... 52 15. Starting the Import Process ...... 53 16. Import SmartGuide...... 54 17. Import from another Repository SmartGuide ...... 55 18. Projects Import Dialog ...... 56 19. Add Project Menu...... 56 20. Add Projects SmartGuide...... 57 21. Problems Indicated in the Workbench ...... 57 22. All Problems Tab ...... 58 23. Add Project Menu...... 59 24. Add Project SmartGuide ...... 60 25. Workbench with Added Projects ...... 61 26. ServletExamples Project ...... 62 27. PartsView Applet in the Visual Composition Editor ...... 63 28. Clicking the Choose Bean Icon ...... 64 29. Choose Bean Dialog ...... 64 30. Choose Class Dialog ...... 65 31. Choose Bean Dialog with PartsCatalog Selected ...... 66 32. PartsCatalog Added to the PartsView Applet...... 66 33. VisualAge for Java IDE Options Menu...... 67 34. Design Time Options Dialog ...... 68 35. Saving a Bean ...... 69 36. Checking the Class Path ...... 70 37. Setting the Width and Height Attributes ...... 71 38. Setting the Class Path ...... 72 39. Select the Projects to be Included in the Class Path ...... 73 40. Project Path and Complete Class Path ...... 74 41. Running the PartsView Applet ...... 75 42. PartsView Applet in the Applet Viewer...... 75 43. Applet Viewer Properties Dialog ...... 76 44. Applet Viewer Properties ...... 76 45. Displaying the AS/400 Parts Data Using the PartsView Applet ...... 77 46. The Java Console Messages...... 78 47. The Applet/Servet Three-Tier Design ...... 79 48. The Views Package ...... 81 49. The PartsView Class ...... 82 50. The actionPerformed Method in the PartsView Class ...... 83
© Copyright IBM Corp. 1999 vii 51. The connEtoC1 Method in the PartsView Class ...... 83 52. The getAppletInfo Method in the PartsView Class ...... 84 53. The getbtnGetParts Method in the PartsView Class...... 84 54. The getData Method in the PartsView Class ...... 85 55. The getIMulticolumnListbox Method in the PartsView Class ...... 86 56. The getPartsCatalog method in the PartsView Class ...... 87 57. The handleException Method in the PartsView Class ...... 87 58. The init Method in the PartsView Class ...... 88 59. The initConnections Method in the PartsView Class ...... 88 60. The dataAccess Package ...... 89 61. The DataAccessor Interface in the dataAccess Package ...... 90 62. The JDBCPartsCatalog Class...... 91 63. The connectToDB Method in the JDBCPartsCatalog Class ...... 92 64. The getAll Method in the JDBCPartsCatalog Class ...... 94 65. The TestPart Class ...... 95 66. The connectToDB Method in the TestPart Class ...... 95 67. The getAll Method in the TestPart Class...... 96 68. The Domain Package ...... 97 69. The Part Class ...... 98 70. The Part Constructor in the Part Class ...... 98 71. The getAttributeString Method in the Part Class...... 99 72. The get Methods in the Part Class ...... 99 73. The set Methods in the Part Class ...... 100 74. The PartsCatalog Class ...... 101 75. The connectToDB Method in the PartsCatalog Class...... 101 76. The defaultDataAccessor Method in the PartsCatalog Class ...... 102 77. The getAll Method in the PartsCatalog Class ...... 103 78. The getDataAccessor Method in the PartsCatalog Class ...... 104 79. The getParts Method in the PartsCatalog Class ...... 104 80. The set Methods in the PartsCatalog Class ...... 105 81. Exporting the Applet Packages ...... 107 82. Export SmartGuide ...... 108 83. The Export to a Jar File Dialog ...... 109 84. Opening the Netscape Java Console ...... 110 85. Netscape Java Console when the PartsView Applet is Running ...... 111 86. Opening the PartsView.html File in the Browser...... 111 87. Java Security Dialog ...... 112 88. PartsView Applet in the Netscape Browser...... 113 89. Microsoft Internet Explorer List of Certificate Authorities ...... 115 90. Enable Tracing of the Applet at Runtime ...... 117 91. Export to a Directory Dialog ...... 118 92. The chkjava Command Security Warning Panel...... 119 93. Java Console with the Trace Messages ...... 121 94. Selecting the Missing Classes in the .class Export Dialog ...... 123 95. Removing Unwanted Entries from the Export List ...... 124 96. Resource Export Dialog ...... 124 97. Setting the Windows NT 4.0 CLASSPATH Environment Variable ...... 127 98. Setting the Name of the jar File...... 131 99. PartsView.html Code before Conversion for the Java Plug-in ...... 134 100.PartsView.html File after Conversion for Use with the Java Plug-in...... 135 101.Java Plug-in HTML Converter Options...... 137 102.Java Plug-in HTML Converter Dialog ...... 138 103.Sample Output of the Generate Log File ...... 139
viii Building AS/400 Internet-Based Applications with Java 104.Advanced Options Dialog ...... 140 105.Microsoft Internet Explorer Security Warning ...... 141 106.Code in the Converted HTML File ...... 141 107.Select Java Plug-in Installation Dialog...... 142 108.Code in the Converted HTML File that is Processed by Netscape Navigator 143 109.Netscape Navigator Plug-in Not Loaded Panel ...... 143 110.Java Plug-in Download Page...... 144 111.Revised Advanced Options Settings for the HTML Converter...... 146 112.Netscape Plug-in HTML File ...... 147 113.Java Plug-in Software License Agreement ...... 148 114.Java Plug-in Choose Destination Location Dialog...... 149 115.Java Console...... 149 116.Windows 95/NT Add/Remove Programs Dialog ...... 150 117.Plug-in Not Loaded Panel ...... 151 118.Netscape Plug-in.html File...... 152 119.About:plugins Feature ...... 153 120.Basic Tab of the Java Plug-in Control Panel ...... 154 121.Advanced Tab in the Java Plug-in Control Panel ...... 155 122.Proxies Tab in the Java Plug-in Control Panel ...... 155 123.Servlet Application ...... 159 124.Servlet Architecture ...... 160 125.Servlet Hierarchy ...... 161 126.Servlets versus CGI.BIN ...... 163 127.Calling a Servlet Directly ...... 165 128.Calling a Servlet Using HTML Files...... 165 129.Calling a Servlet Using SHTML Files...... 165 130.HelloWorldServlet ...... 166 131.ServletExamples Project ...... 167 132.Java Applet/Servlet Design ...... 168 133.PartsServlet Class ...... 169 134.Servlet init Method ...... 169 135.The doGet Method...... 170 136.The outputHeader Method...... 170 137.The outputPartsInformation Method ...... 171 138.The doGet Method Output ...... 171 139.Enhanced Servlet ...... 172 140.The doPost Method ...... 173 141.Servlet HTML File (Parts.html) ...... 174 142.Three-Tier Servlet Architecture ...... 175 143.Enhanced Servlet ...... 177 144.Two-Tier Servlet Architecture ...... 177 145.The Company Structure...... 179 146.RPG Application Flow ...... 181 147.Parts Order Entry...... 182 148.Select Customer ...... 183 149.Parts Order Entry...... 184 150.Select Part ...... 185 151.Parts Order Entry...... 185 152.Parts Order Entry...... 186 153.Change Selected Order...... 186 154.Completed Order ...... 187 155.Printed Order ...... 187 156.Table Relationships ...... 188
ix 157.Toolbox Applet ...... 194 158.Cart Applet ...... 194 159.Placing an Order...... 195 160.Order Confirmation ...... 195 161.Status Applet ...... 196 162.Shopping Application Design ...... 197 163.ToolboxApplet Package ...... 198 164.SelectedItems Class Definition...... 199 165.The getVector Method ...... 199 166.The clear Method ...... 200 167.The addSelectedRow Method ...... 200 168.The ItemsDb Class Definition ...... 201 169.The connect Method...... 203 170.The disconnect Method ...... 203 171.The finalize Method ...... 204 172.The fetchNextItem Method ...... 205 173.The getItem Method ...... 205 174.The getItems Method ...... 206 175.The quantityInHand Method ...... 207 176.The verifyCustomer Method ...... 207 177.The checkOrderStatus Method...... 209 178.ToolboxAppletExample Class Definition...... 209 179.The AddAllRows Method ...... 210 180.The getSelectedIndexes Method ...... 210 181.Toolbox Applet in the VCE ...... 211 182.CartApplet Class Definition...... 212 183.The showCart Method ...... 213 184.The Cart Applet in the VCE ...... 214 185.OrderStatus Class Definition ...... 215 186.The fillListbox Method...... 216 187.Order Status Applet ...... 216 188.The apptest\ToolboxApplet Directory ...... 217 189.The apptest Directory ...... 218 190.Order.htm ...... 219 191.Order1.htm ...... 219 192.Status.htm ...... 219 193.Shopping Applet Running under Netscape Navigator ...... 220 194.Servlet Sign On Window...... 222 195.Servlet Application Menu Window ...... 223 196.Query Recall Window ...... 224 197.Query Builder Window ...... 224 198.Query Results...... 225 199.Query Wizard Table Prompt ...... 226 200.Select Fields Prompt Window...... 226 201.Select Conditions Prompt Window ...... 227 202.Select Order Prompt Window ...... 228 203.Query Results...... 229 204.User ID Prompt...... 230 205.Print Jobs By User ...... 230 206.Output Queues Display ...... 231 207.Print Jobs By Output Queue...... 231 208.AS/400 Integrated File System Directories...... 232 209.Directory Listing ...... 232
x Building AS/400 Internet-Based Applications with Java 210.AS/400 Performance Information ...... 233 211.AS/400 Command ...... 233 212.AS/400 Command Output ...... 234 213.Change Password ...... 234 214.SignOn doGet Method ...... 236 215.SignOn genSignonForm Method ...... 237 216.Generated Sign On HTML ...... 238 217.SignOn doPost Method ...... 239 218.SignOn genMain Method...... 240 219.Application Menu HTML ...... 240 220.Application Menu ...... 241 221.The PerfMon Class doGet Method ...... 242 222.System Performance Information ...... 243 223.HTML Generated by the getSavedQueries Method ...... 244 224.Saved Queries Window ...... 245 225.HTML Generated by the queryPrompt Method ...... 246 226.Query Statement Window ...... 247 227.Query Results ...... 248 228.HTML File Generated by the wizPrompt Method...... 249 229.Enter Table Name Prompt ...... 249 230.HTML Generated By the wizColInfo Method ...... 250 231.SQLWizard Applet ...... 251 232.HTML File Generated by the wizWhere Method ...... 252 233.SQLWhere Applet ...... 253 234.HTML File Generated by the wizOrder Method ...... 254 235.SqlOrder Applet ...... 254 236.HTML File for the queryPrompt Method ...... 255 237.Query AS/400 Database ...... 256 238.SQL Result ...... 257 239.ServletExpress\servlets Directory ...... 258 240.Applet Directory ...... 258 241.apptest Directory ...... 258 242.\QIBM\ProdData\IBMWebAS\servlets Directory ...... 259 243.Applet Directory ...... 260 244.The apptest Directory ...... 260 245.Internet Security Elements...... 262 246.Transaction Security ...... 262 247.Verifying Identity—Digital Certificates and Digital Signatures ...... 264 248.HTTP Server Using SSL ...... 266 249.Accessing a Secure HTTP Session...... 267 250.AS/400 Tasks Page...... 270 251.Create an Intranet Certificate Authority ...... 271 252.CA Certificate Created Successfully ...... 271 253.Certificate Authority Policy...... 272 254.Create a Server Certificate Page...... 273 255.Server Certificate Created Successfully Page...... 273 256.Create a Server Certificate with an Existing Intranet CA ...... 274 257.HTTP Server Configuration ...... 275 258.Security Configuration Page ...... 276 259.Work with Server Instances...... 277 260.Requesting a Certificate from VeriSign or other Internet Certificate Authority278 261.Request a Server Certificate from an Internet CA ...... 279 262.Server Certificate Request Generated by DCM...... 279
xi 263.Receiving a Server Certificate Issued by an Internet CA ...... 280 264.Key Management Page ...... 281 265.New Site Certificate ...... 282 266.New Site Certificate Information ...... 282 267.View a Certificate ...... 283 268.New Site Certificate Acceptance Dialog ...... 283 269.Netscape Certificate Warning Dialog ...... 284 270.Netscape Security Information Dialog ...... 284 271.PartsServlet Running under SSL ...... 285 272.Domino Go Webserver Initial Screen ...... 287 273.Configuration and Administration Window ...... 288 274.Domino Go Routing Table ...... 289 275.ServletExpress Services Dialog ...... 290 276.ServletExpress Setup Window ...... 291 277.ServletExpress Add Servlet Dialog...... 292 278.ServletExpress Servlet Configuration Dialog ...... 293 279.Browser-based HTTP Server Configuration Program ...... 295 280.HTTP Server Directives to Enable WebSphere ...... 296 281.JVM Properties File ...... 297 282.WebSphere Sign On Screen ...... 298
xii Building AS/400 Internet-Based Applications with Java Tables
1. Parameters Used with the QzhbCgiParse API...... 18 2. The CGII0200 Format ...... 19 3. Parameters Used with the QtmhWrStout API ...... 20 4. Summary of OS/400 Pre-V4R3 and V4R3 HTTP Server Components ...... 42 5. ServletExamples Packages, Classes, and Interfaces ...... 62 6. Methods Used in the PartsView Class ...... 82 7. Methods Defined in the DataAccessor Interface ...... 89 8. Methods Used in the JDBCPartsCatalog Class ...... 90 9. Methods Used in the TestPart Class ...... 95 10. Methods Used in the Part Class...... 97 11. Methods Used in the PartsCatalog Class ...... 100 12. Operating Systems and Browser Versions Supported by the Java Plug-in . . 134 13. Summary of Packages, Classes, and Interfaces Used for the PartsServlet . 167 14. District Table Layout (Dstrct) ...... 189 15. Customer Table Layout (CSTMR) ...... 189 16. Order Table Layout (ORDERS) ...... 190 17. Order Line Table Layout (ORDLIN)r ...... 190 18. Item Table Layout (ITEM) ...... 191 19. Stock Table Layout (Stock) ...... 191 20. Database Terminology ...... 192 21. ItemsDb Class Variables ...... 202 22. Applet HTML Files ...... 218
© Copyright IBM Corp. 1999 xiii xiv Building AS/400 Internet-Based Applications with Java Preface
The AS/400 system, the Internet, and Java. What a powerful combination! If you are interested in enabling your company for the world of e-business, this redbook is for you. It is intended for anyone who wants to design and build AS/400 Internet- or intranet-based applications using Java.
This redbook focuses on building applets and servlets that access AS/400 resources. It provides many practical programming examples with detailed explanations of how they work. These examples are also available for you to download from our Internet site. This redbook gives you a fast start on your way to using Java, the Internet, and the AS/400 system.
The Team That Wrote This Redbook This redbook was produced by a team of specialists from around the world working at the International Technical Support Organization Rochester Center.
Bob Maatta is a Senior Software Engineer from the United States at the International Technical Support Organization, Rochester Location. He writes extensively and teaches IBM classes worldwide on all areas of AS/400 client/server and application development. Before joining the ITSO in 1995, he worked in the U.S. AS/400 National Technical Support Center as a Consulting Market Support Specialist. He has over 20 years of experience in the computer field and has worked with all aspects of personal computers since 1983. He is a Sun Certified Java Programmer and a Sun Certified Java Developer.
Markus Abegglen is a Project Leader at DV Bern AG, an IBM Business Partner in Switzerland. He has eight years of experience in the AS/400 area, as well in object technology. He holds a higher national degree in Economics and Computer Science. He has worked on several projects that are based on VisualAge for Java.
Craig Pelkie is a consultant based in Southern California. He is the editor of the NEWS/400 newsletter Client Access & Windows Solutions, and the past editor of Midrange Computing’s Client Access Expert. He frequently leads seminars on Client Access, AS/400 web-enablement techniques and AS/400 client/server programming using Visual Basic. He is the author of the training manual Using Microsoft Visual Basic with the AS/400 (http://www.vb400.com) which was used in labs at IBM Rochester Partners In Development.
Brian Skaarup is a software developer for EDB Gruppen Systems A/S, a Danish business partner. He has worked in the R&D department for the last eight years. His areas of expertise include client/server application design and development using C, C++, and Java.
Daniel Stucki is a Systems Engineer at DV Bern AG, an IBM Business Partner in Switzerland. He has nine years of experience in the AS/400 area as well in object technology. He also holds a degree in Computer Science from the Berne Institute of Technology. He has worked on several projects that are based on VisualAge for Smalltalk and VisualAge for Java.
© Copyright IBM Corp. 1999 xv Thanks to the following people for their invaluable contributions to this project:
Marcela Adan ITSO Rochester
Chi Lam IBM Rochester Laboratory
Gary Mullen-Schultz IBM Rochester - Partners in Development
Schuman Shao IBM Rochester Laboratory
Comments Welcome Your comments are important to us!
We want our redbooks to be as helpful as possible. Please send us your comments about this or other redbooks in one of the following ways: • Fax the evaluation form found in “ITSO Redbook Evaluation” on page 317 to the fax number shown on the form. • Use the electronic evaluation form found on the Redbooks Web sites: For Internet users http://www.redbooks.ibm.com For IBM Intranet users http://w3.itso.ibm.com • Send us a note at the following address: [email protected]
xvi Building AS/400 Internet-Based Applications with Java Chapter 1. AS/400 Internet Application Development Overview
Let’s put our business on the Internet! Those words, spoken by the company president to the chief information officer (CIO), the CIO to the systems analysts, and the analysts to the programmers, are sure to cause a great deal of excitement, concern, confusion, and doubt. After all, it is one thing to surf the Web and find many examples of good and not-so-good sites to emulate. It is quite another issue to know where to start with your Internet development project and how to proceed.
There are many technical problems that must be resolved to reach the point where your customers can successfully use your corporate Web site to interact with your company. Some of the issues you need to address are: • What hardware and software do you need on your AS/400 system so that it can be connected to the Internet and function as a Web server? • What do you need to know about securing your AS/400 system, given that you need to allow access to data stored on the system? • What skills are required to create dynamic Web pages that work with the AS/400 system? If you do not have the skills, what direction should you take to learn what you need to know? • Where does Java fit into all of this? How does Java make it easier to work with Internet applications?
Although the answers to all of those questions are not in this redbook, this document shows you how Java can be used with the AS/400 system to create highly functional, dynamic Web pages. You learn how you can use Java in client-side applets and how Java servlets can be used on the AS/400 system to access the database and send responses to the client.
In this chapter, you explore four Internet application development approaches to use with the AS/400 system: • Net.Data • Common Gateway Interface (CGI) programming • Java applets • Java servlets
Upon finishing this chapter, you gain a better idea of which technique to use when you develop your Internet application.
1.1 From Server to Browser and Back—Fundamental Concepts Before you can start coding an Internet application for the AS/400 system, you need to clearly understand how a request is sent from the browser to the IBM HTTP Server for AS/400, how the server invokes a program to process the request, and how the response from the program is returned to the browser. Although there are hundreds of configuration decisions that must be addressed, we assume that you already have the IBM HTTP Server for AS/400 connected to the Internet and configured to serve Web pages.
© Copyright IBM Corp. 1999 1 See how a Web serving request is processed. Figure 1 on page 2 shows how the request flows from the browser to the server, where the Web serving application accesses the database, prepares the response, and sends it back to the browser.
IBMIBM HTTPHTTP ServerServer forfor AS/400AS/400
"Show"Show meme X"X"
"Here's"Here's X"X"
Some Process
DB2/400
Figure 1. How an HTTP Server Processes a Request for a Dynamic Web Page
1.1.1 The Requesting Web Page The user starts at the requesting Web page. The page appears when a user enters a URL in the browser’s location or address field, or clicks a link on another Web page.
Web pages that allow user input are called forms. A form contains one or more elements that the user interacts with, for example, text fields, list boxes, check boxes, and buttons. When the user clicks a submit button, the browser formats a stream of data that contains the data the user entered or selected on the form. The stream of data is sent to the IBM HTTP Server for AS/400.
1.1.2 The Web Serving Application Along with the data, the browser sends the name of the application that is to be invoked on the AS/400 system to process the data. The application name is included in the Hypertext Markup Language (HTML) code that was originally sent to the browser to display the Web page. The IBM HTTP Server for AS/400 invokes the application.
1.1.2.1 Input Data from the Form There are two different methods used to make input data from the form available to the Web serving application program. The HTML form is coded to indicate which method to use.
2 Building AS/400 Internet-Based Applications with Java The first method is the Get method. All of the data from the form is available to the Web serving application program in an environment variable called QUERY_STRING. The Web serving application program retrieves the contents of the environment variable so that it has access to the data. The Get method is limited to return 1024 bytes of data from the browser to the Web serving application program. Because the data also contains field names to identify each data element, the actual length of the data that can be entered by the user is less than 1024.
The second method is the Post method. With this method, data from the browser is available to the Web serving application program in a stream file called Standard Input (STDIN). Because the data is in a file, there is no limit to the length of the data that can sent from the browser. The Post method is the preferred method for returning form data from the browser.
Regardless of the method used, the data is HTTP encoded. Figure 2 shows a sample of data returned from a name and address Web form.
Figure 2. Form Data in HTTP Encoded Format
There are a few points to notice about the data in HTTP encoded format: • The IBM HTTP Server for AS/400 takes care of the required ASCII to EBCDIC translation. Data that the user enters in the browser is sent to the server using the ASCII character set. Because the AS/400 works with the EBCDIC character set, there needs to be a translation between the two.
AS/400 Internet Application Development Overview 3 • The field names used on the form are included in the data and precede the value that the user entered. The field name and value are separated by an equals sign. • Blank spaces that the user entered are replaced with plus signs (+). • The end of each data field is delimited by the ampersand (&) character. • Special characters are encoded with hexadecimal values. For example, the area code in the telephone number (line beginning 121 in Figure 2) has hexadecimal values for the parentheses: – %4D is used for the ( character – %5D is used for the ) character
One of the main jobs of the Web serving application program is to make sense of the HTTP encoded data. Because all AS/400 Web programmers have to deal with this requirement, Web programming tools that are available with the IBM HTTP Server for AS/400 include functions to interpret the HTTP encoded data and return it to the Web serving application program in data fields with which the program can work.
1.1.2.2 Processing the Request Once the data is parsed into fields, the program can begin working on the request. At this point, conventional AS/400 programming techniques can be used. For example, the Web serving application program can: • Use native database access techniques to retrieve records from the database. • Use SQL statements to query the database or perform database updates. • Call other programs on the AS/400 system to perform additional functions required to construct the response. • Issue communications requests to other AS/400 systems or other database platforms to get additional data.
The Web serving application program has complete access to all of the AS/400 system facilities to which it is authorized.
1.1.2.3 Returning a Response to the Browser Assume that the user’s request to the IBM HTTP Server for AS/400 was accepted by the server and that the server did not send an error response to the browser. It is now up to the Web serving application program to prepare a response that the browser understands and send it to the browser.
The response is HTML code. HTML is simply text that includes tags to identify elements on a Web page, such as the title, headers, tables, and graphics, and the data that is displayed on the page. Although most Web pages that you view when Web surfing are made up of static HTML, it is entirely possible and quite feasible to generate HTML on an "as-requested" basis, as in the example described in this chapter. It is a relatively easy programming job to construct HTML since it only requires simple string handling operations to put together the combination of HTML tags and data.
The response HTML and data can be as simple or as complex as required. For example, a simple listing of items can be done using the monospacing HTML tags. Or, you may choose to present the list in a nicely formatted table. The
4 Building AS/400 Internet-Based Applications with Java response may be another form to prompt the user for additional information. You can also include graphics, scripting, or applets in the response.
As each line of HTML code is constructed, it is written to the Standard Output (STDOUT) file. The STDOUT file is used by the Web serving application program as a conduit back to the browser, which is waiting for the response from the program. The IBM HTTP Server for AS/400 translates the response HTML in STDOUT from EBCDIC to ASCII and sends it back to the browser.
At this point, the cycle is complete. The user sent their request, which was successfully interpreted and responded to. The Web serving application program retrieved and formatted the requested data. The IBM HTTP Server for AS/400 sent the response back to the browser. The user is now free to review the response and make additional requests with their browser.
1.2 AS/400 Internet Application Development Techniques Before you start working on your Internet application, you need to be clear about what your options are. If you are somewhat uncertain about what the best option is, you are not alone. Many developers are in the same position, trying to assess what is the best technique to use.
As with any other programming job, there is no definitive "best" technique, but rather a series of trade-offs. The technique you choose should be based on: • Your understanding of the trade-offs • The ability of the selected technique to let you accomplish what must be done • The amount of effort it will take to develop the application • The anticipated usage of the application • The availability of other approaches that may be used to develop the application
We address the last point first, so that it is no longer a factor in your decision.
1.2.1 Other Approaches for Internet Applications In addition to directly programming the AS/400 system for Web serving, which is the focus of this redbook, there are two other approaches to consider: • Locating the application on a different server • Using the Lotus Domino server available for the AS/400 system
1.2.1.1 Locating the Application on a Different Server It is not unusual for a company to place their Web serving application on an entirely different host from the production database. For example, many companies use Windows NT Server or UNIX servers for Web applications. It is also possible to use another AS/400 system as the Web serving host. Since you are then developing the application on an AS/400 system, we consider that solution to be the same as developing the application on the AS/400 system that hosts the database.
When you introduce an entirely different type of server, you need to resolve the problem of making your production database available to that server. For real-time access, your application may use ODBC or communications programming to retrieve data from the AS/400 system database to the Web
AS/400 Internet Application Development Overview 5 serving application. For applications that do not require real-time access to the database, you can replicate the database from the AS/400 system to the Web serving host as required.
If you adopt this approach, your programming tasks are simply relocated to the other server. Also, you probably need to perform more programming and certainly more management of the servers to coordinate access to the database. Nevertheless, you may choose to implement your Web serving application on another type of server because of capacity, availability of programming skills, or for security reasons.
1.2.1.2 Using the Lotus Domino Server for the AS/400 System The AS/400 system now supports a native implementation of the Lotus Domino server. This provides a very attractive option. This is because performance and the ability to access the AS/400 system database is much enhanced compared to the implementation of Domino on the Integrated PC Server (IPCS).
Domino includes a full-featured application development environment, in addition to the rich functionality provided in the product itself. For many AS/400 system Web applications, Domino is the best choice.
An important point to note is that Domino and other AS/400 system Web development techniques are not mutually exclusive. If you choose to implement Domino for AS/400 system Web serving applications, you may still find the material in this redbook useful for applications that run outside of the Domino environment.
1.2.2 Four Tools for Internet Development on the AS/400 System At this point, you can consider the tools that are available for developing an Internet application on the AS/400 system, using the IBM HTTP Server for AS/400. The tools that are examined include: • Net.Data, included with the IBM HTTP Server for AS/400 • CGI programs, which can be written in traditional AS/400 system programming languages such as RPG and COBOL • Java applets, which can use the AS/400 Toolbox for Java to communicate from an applet running in a browser to the AS/400 system • Java servlets, which are available with OS/400 V4R3
Each of these tools require programming skills. In addition, you need to know enough HTML to achieve the effect you want, since you will use a tool to generate HTML to present the data retrieved from the AS/400 system.
1.3 Net.Data Net.Data is a Common Gateway Interface (CGI) program provided with the AS/400 TCP/IP Connectivity Utilities (5769-TC1). Net.Data uses macros that you develop as input to the CGI program. The CGI program uses the macro to: • Send HTML to your browser • Run SQL commands • Call system services such as programs compiled in other languages
6 Building AS/400 Internet-Based Applications with Java Net.Data is the follow-on product to what was originally known as DB2WWW. The Net.Data CGI program itself is named DB2WWW. You occasionally see references to the DB2WWW product in the Net.Data documentation.
Note The primary documentation for working with Net.Data on the AS/400 system is available at the AS/400 Net.Data Web site located at: http://www.as400.ibm.com/netdata
The following manuals are available at that site: • Net.Data Administration and Programming Guide • Net.Data Language Environment Reference • Net.Data Reference
1.3.1 Why Use Net.Data If you already know RPG, COBOL, C, or Java, you may wonder why you would use Net.Data, since you can develop AS/400 CGI programs using traditional AS/400 programming languages. However, when you use those languages, you are responsible for programming some of the low-level details required by the HTTP protocol. For example, you need to parse the input data that is sent to the server from an HTML form. You also need to take special care to send any required HTML headers back to the browser along with your application HTML and data, so that the browser knows how to work with the server response.
For RPG, COBOL, and C, you need to compile the programs before you can test them. If you need to make even minor changes, you need to repeat the edit, compile, and test cycle.
You may find that Net.Data provides a more simple alternative to working with AS/400 languages, especially if you simply want to retrieve and display data from the AS/400 database. Some of the characteristics of Net.Data that make it easier to use are: • Net.Data is interpreted, not compiled. You can develop a Net.Data macro more rapidly than the equivalent compiled program. You can also make changes much more quickly. For example, adding or changing HTML statements in a Net.Data macro is trivial, and you can test the change immediately. • Net.Data provides tremendous built-in support for working with the results of SQL queries. For example, Net.Data can automatically format the results of an SQL SELECT statement into an HTML table. You do not have to code the HTML for the table. You simply code the SELECT statement. • Net.Data takes care of getting and parsing requests from the browser and preparing output to return to the browser. You simply code the HTML that you want sent to the browser and indicate what data is to be displayed. You do not have to code the lower-level HTML to deal with headers.
1.3.2 Net.Data Processing To work with Net.Data effectively, you must understand how the CGI program DB2WWW interacts with:
AS/400 Internet Application Development Overview 7 • Your incoming request from the browser • The IBM HTTP Server for AS/400 • Net.Data INI file • The macro itself • The DB2/400 database and other system services
Net.Data Processing 3. Retrieve INI settings
INI 4. Macro/Section hello.mbr/input Browser http://myAS400/netdata/hello.mbr/input 5. Retrieve Macro
1. Request URL 2. DB2WWW Macro invoked source DB2WWW 6. Go to INPUT se cti on, sta rt processing
7. Get requested data
10. Returns to Browser
9. Generated HTML DB2/400
IBM HTTP Server for AS/400 Other 8. Other AS/400 Services services as requested
Figure 3. How Net.Data Processes a Macro and Generates a Response
Assuming that Net.Data is properly configured and you have a macro that you want to run, here is the process that occurs when you invoke a Net.Data macro. The following numbers correspond to the steps shown in Figure 3: 1. A Net.Data macro is requested on an incoming URL. You start a Net.Data macro by entering the URL containing the request in your browser's address entry area or you click on a link on a Web page that contains the request. The request is sent to the IBM HTTP Server for AS/400 the same as any other request. 2. The DB2WWW CGI program is invoked. The IBM HTTP Server for AS/400 determines from the incoming URL that the request is for Net.Data. At this point, the IBM HTTP Server for AS/400 invokes the DB2WWW CGI program. As with other requests to the IBM HTTP Server for AS/400, you need HTTP Server configuration directives so that the IBM HTTP Server for AS/400 knows how to handle the incoming request. To process Net.Data macros, you need at least one EXEC directive and you usually have at least one MAP directive. 3. Net.Data configuration options are retrieved from the INI file. Upon starting, the DB2WWW CGI program retrieves initialization options from the optional INI file, which is located in the same library as the DB2WWW
8 Building AS/400 Internet-Based Applications with Java program. If you do not create an INI file, the URLs that you use to invoke a Net.Data macro are considerably more complicated. 4. The macro and start-at section within the macro are identified. When the IBM HTTP Server for AS/400 invokes the DB2WWW CGI program, it passes the part of the incoming URL that identifies the macro to be invoked and the start-at section within the macro to the program. At this point, the DB2WWW program determines where on the system the macro source file is located. If you are using an INI file, the DB2WWW program uses the MACRO_PATH definition within the INI file to resolve the location of the macro. 5. The macro is retrieved. The DB2WWW CGI program now retrieves the macro. All Net.Data macros are stored in text format. 6. DB2WWW starts the execution of the macro at the start-at section. The DB2WWW CGI program parses the macro. Any global function calls and definitions in the macro are processed. Next, the DB2WWW CGI program goes to the start-at section that was specified on the incoming URL and starts processing the directives that are in that section. The start-at section is typically an HTML block that contains statements describing the initial page to be sent to the browser. For example, for a database query application, the start-at section may contain HTML that prompts the user for selection criteria. 7. DB2/400 data is processed with SQL statements. If there are any SQL statements or Net.Data function calls to other AS/400 system services, those statements or function calls are now processed. 8. Other system services are invoked. In a typical Net.Data macro, you embed SQL statements or function calls within HTML statements. Net.Data runs the SQL statement or function call at the point where it is encountered. The resulting HTML sent to the browser can include your headings and footings with the merged output of an SQL statement or function call. 9. The resulting HTML is returned to the IBM HTTP Server for AS/400. After processing the section and running SQL statements or other functions, the resulting HTML is returned from the DB2WWW CGI program to the IBM HTTP Server for AS/400. 10.The resulting HTML is sent back to the browser. The IBM HTTP Server for AS/400 sends the completed HTML page back to the browser. At this point, the process is complete. The user can request another Net.Data macro invocation, which starts the process over again.
1.3.3 How Net.Data Macros are Invoked Net.Data macros are invoked from conventional URLs. The URL can be entered directly into the browser's address entry area or can be provided in the form of a link on an HTML page.
Here is a sample URL used to invoke the Net.Data sample application: http://myAS400/netdata/nd_parts.mbr/input
AS/400 Internet Application Development Overview 9 There are three parts of the URL that are particularly important for Net.Data: • Location of DB2WWW CGI program—In the sample URL, the /netdata part points to the location of the DB2WWW CGI program. The IBM HTTP Server for AS/400 expands this part of the URL using the MAP directive in the HTTP Server configuration file: Map /netdata/* /QSYS.LIB/NETDATA.LIB/DB2WWW.PGM/* The final asterisk character for both the source and replacement strings indicates that any input on the incoming URL following the /netdata/ string is to be appended to the end of the expanded directory string. The expanded URL now looks like this: http://myAS400/QSYS.LIB/NETDATA.LIB/DB2WWW.PGM/nd_parts.mbr/input • Name of macro to invoke—The string /nd_parts.mbr identifies the name of the macro file that the DB2WWW CGI program is to load and process. Since the Net.Data macro is stored in an AS/400 source file in the AS/400 library file system, the .MBR suffix is required. If you request a macro that is stored in an AS/400 IFS directory, the suffix is the file extension. For example, if you store your Net.Data macros as .TXT files, include the .TXT suffix in the URL you use to invoke the macro. • Start-at section in macro—Because a Net.Data macro can be quite long and include several different sections, you need to indicate to the DB2WWW CGI program where it is to start processing. In the sample URL, this is indicated with the /input string. It is conventional, although not required, that you start processing a Net.Data macro at a section labeled INPUT.
1.3.4 A Sample Net.Data Macro The following sample Net.Data macro shows how you can use Net.Data to present a prompting page to the requester. Then, you can use input from the page to retrieve and display database records from the AS/400 system.
Figure 4 on page 11 shows the prompting page that is displayed when the user initially enters the URL.
10 Building AS/400 Internet-Based Applications with Java Figure 4. Prompting Page Displayed by the Net.Data Macro
The user can accept the default of *ALL for the part number selection or enter a specific part number and then the Get Parts Information button. The Net.Data macro responds by querying the database and displaying the page shown in Figure 5.
Figure 5. Parts File Listing Generated by the Net.Data Macro
AS/400 Internet Application Development Overview 11 1.3.5 Source Code for the Net.Data Sample Macro The following source code is the complete Net.Data macro used to generate the prompting page and the parts list shown in Figure 4 and Figure 5 on page 11. If this is your first look at Net.Data, you probably think this is a strange language. However, if you glance through the code, you can start identifying different types of language elements and constructs: • Comment lines start with the %{ characters and end with the %} characters. • Code blocks begin with %define, %message, %function, and %html. • SQL statements are embedded in the macro and can include substitution variables (for example, $(partno)). • HTML statements are embedded in the macro. Net.Data function calls can also be included with the HTML to generate additional HTML as the macro is processed.
Although we do not explain every detail of the macro in this redbook, we look at some of the sections of the macro so that you have an understanding of how it works.
%{------%} %{ Net.Data macro ND_PARTS -- display Parts in HTML table %} %{------%} %define{ DATABASE = "*LOCAL" DTW_HTML_TABLE = "YES" %}
%message { -204 : "Error -204: Table not found" 100 : "Warning 100: Record not found" : Continue +default : "Warning $(RETURN_CODE)" : Continue -default : "Unexpected SQL error $(RETURN_CODE)" : Exit %}
%{------%} %{ Function RUNSQL - Called from GETDATA, get a part %} %{------%} %function(DTW_SQL) RUNSQL() {
select * from apilib.parts where partno = $(partno)
%}
%{------%} %{ Function RUNSQLALL - Called from GETDATA, get all parts %} %{------%} %function(DTW_SQL) RUNSQLALL() {
select * from apilib.parts order by partno
%}
%{------%} %{ HTML section INPUT - loaded by initial URL %} %{------%} %html (INPUT) {
%{------%} %{ HTML section GETDATA - called when Submit button is clicked. %} %{------%} %html (GETDATA) {
Parts File Listing
%if ($(partno) == "*ALL") @RUNSQLALL() %else @RUNSQL() %endif
%}
1.3.5.1 The HTML INPUT Section Macro processing starts at the INPUT section. This is because the requesting URL identified the INPUT section as the start-at section (see the URL in Figure 4 on page 11).
Because this section is an HTML section (indicated by the %html block type identifier), the macro includes HTML statements that are sent to the browser. The HTML in the INPUT section is used to format the prompting Web page.
The INPUT section includes three statements that are used to process the prompting form: •
Figure 7. HTML Code Used to Display the Prompting Page for the CGI Program
There are three HTML statements used to process the form:
Figure 128. Calling a Servlet Using HTML Files
• Using the HTML
Figure 129. Calling a Servlet Using SHTML Files
In this case, you have to use the file extension .shtml instead of .html or .htm.
4.3 A Simple Servlet The servlet example in Figure 130 on page 166 displays "Hello world" in a browser.
Introduction to AS/400 Servlets 165 import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
public class HelloWorldServlet extends HttpServlet{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out;
res.setContentType("text/html"); out = res.getWriter();
out.println(""); out.println("
Hello World
"); out.println(""); } }Figure 130. HelloWorldServlet
To call the servlet directly, you can specify the servlet name directly in the URL as shown in the following example: http://
The HelloWorldServlet demonstrates some of the basic concepts, as shown in the following sequence, that are used when creating HTTP servlets: 1. We import support classes from the javax.servlet and javax.servlet.http packages. 2. The HelloWorldServlet extends the HttpServlet class, which implements the Servlet interface. 3. The doGet method is called when a client makes a GET request (the default HTTP request method). If the servlet is called directly, the doGet method is called. 4. We override the doGet method to handle application processing. 5. Two parameters are passed in to the doGet method: • HttpServletRequest req—Encapsulates the input • HttpServletResponse res—Encapsulates the output 6. Because text data is returned to the client, the reply is sent using a print writer object obtained from the HttpServletResponse object: a. We declare a PrintWriter object named out. b. We set the response content to "text/html". c. We use the HttpServletResponse getWriter method to create the print writer named out. d. We use the println method to write HTML tags. 7. The HMTL tags are rendered by the browser.
4.4 Developing the Servlet Application This section explains the conversion of the applet (discussed in Chapter 3, “Introduction to AS/400 Applets” on page 51) to a servlet.
166 Building AS/400 Internet-Based Applications with Java The PartsServlet servlet was created in VisualAge for Java. Figure 131 shows a view of the ServletExamples project with the servlets package expanded.
Figure 131. ServletExamples Project
Table 13 briefly describes the packages, classes and interfaces used.
Table 13. Summary of Packages, Classes, and Interfaces Used for the PartsServlet ServletExamples Project
Package Class/Interface Description
dataAccess DataAccessor Interface used to define methods that must be implemented by classes in this package.
JDBCPartsCatalog Used to connect to AS/400 system database. Returns a vector of parts.
TestPart Used to simulate a connection to a database. Returns a vector of parts.
domain Part Represents a row of part data retrieved from the database.
PartsCatalog Determines which data source to get part data from. Gets parts from the selected data source and returns a vector of parts data.
Introduction to AS/400 Servlets 167 ServletExamples Project
Package Class/Interface Description
views PartsView The visible part of the applet. Includes the parts listbox and the button to start the query.
servlets PartsServlet Provides the servlet support.
Although the application was initially designed, tested, and used as an applet, the intention was to create a body of reusable code that can be used when the application is migrated to a servlet. By adopting the three-tier architecture shown in Figure 132, the application can be easily changed.
Java Applet/Servlet design
servlet views Package Package End User interface
domain Package Application Logic
dataAccess Data Access Package
JDBCPartsCatalog Other data sources: class TestPar t -- DDM class -- Stored Procedures -- Data Queues
Figure 132. Java Applet/Servlet Design
In fact, it is quite easy to change the application at any of the three tiers. In addition to changing the end user interface code to support an applet or a servlet presentation, the data source can be changed in the data access layer without affecting the other two layers. Also, if any of the application logic needs to be changed, the changes can be made at that layer without affecting either the data access or end user interface layers.
The application is well positioned for change if a different data access technique is used. For example, the IBM AS/400 Toolbox for Java supports record-level access using the AS/400 system Distributed Data Management (DDM) server, program call, and data queues. If you decide to change from the Java Database Connectivity (JDBC) technique, you only need to code your new data access class so that it returns the same type and format of data to the application logic
168 Building AS/400 Internet-Based Applications with Java layer. The applet uses the JDBCPartsCatalog and TestPart classes. The TestPart class is used to simulate a connection to a data source.
For detailed information about the dataAccess package, the views package, and the domain package, refer to Chapter 3, “Introduction to AS/400 Applets” on page 51. This chapter covers the servlet package.
4.5 Migrating the Applet to a Servlet The servlet application is contained in a class named PartsServlet, which resides in the servlet package.
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class PartsServlet extends HttpServlet { private domain.PartsCatalog partsCatalog; }
Figure 133. PartsServlet Class
Note the following points in Figure 133: • A private instance variable named partsCatalog is in the class definition. Because of our object-oriented design, we can use the same domain package and dataAccess package that we used for the applet. Here, we declare a PartsCatalog object from the domain package. • We also import the javax.servlet and javax.servlet.http packages. To use these packages inside VisualAge for Java, we restore the Sun JSDK class libraries project from the repository.
public void init (ServletConfig config) throws ServletException { super.init(config); log("PartsServlet: init()..."); partsCatalog = new domain.PartsCatalog(); partsCatalog.connectToDB(); log("PartsServlet: init() executed."); return;
Figure 134. Servlet init Method
The init method is called when the servlet is started. Note the following steps: 1. We instantiate the PartsCatalog object named partsCatalog. 2. We call the connectToDB method. This loads the JDBC driver into the JVM and performs any required JDBC initialization. 3. We use the log method to write messages to the log. This may be useful for debugging an application.
Introduction to AS/400 Servlets 169 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { log("PartsServlet: doGet()..."); // set the MIME type to text/html response.setContentType("text/html"); // create the output stream ServletOutputStream out = response.getOutputStream(); Vector parts = null; try { log("PartsServlet: doGet(), try{} block ..."); // write the HTML header to the output stream outputHeader(out);
parts = partsCatalog.getAll(); log("after get all..."); // write the HTML table to the output stream outputPartsInformation(out, parts); close(out); log("PartsServlet: doGet(), try{} block executed."); return; } catch(Throwable e){ printError(out, e); } }
Figure 135. The doGet Method
The doGet method is used to retrieve all the records from the Parts database file and display them in a browser.
private void outputHeader(ServletOutputStream printStream) throws IOException { log("PartsServlet: outputHeader()..."); printStream.print("
Figure 136. The outputHeader Method
The outputHeader() method is called to create the HTML tags, which, when sent to the browser, produce the heading.
We call the partsCatalog object’s getAll method to retrieve all the records from the database. The getAll method returns a Vector.
170 Building AS/400 Internet-Based Applications with Java private void outputPartsInformation(ServletOutputStream printStream, Vector partsVector) throws IOException { log("PartsServlet: outputPartsInformation()..."); Enumeration parts = partsVector.elements(); printStream.println("
Number | Description | Quantitiy | Price | Date | "); printStream.println("" + aPart.getNumber() + " | "); printStream.print("" + aPart.getDescription() + " | "); printStream.print("
---|
Figure 137. The outputPartsInformation Method
We call the outputPartsInformation to build an HTML table which contains all the records. We then send the HTML table to the browser for display. The output is shown in Figure 138.
Figure 138. The doGet Method Output
Introduction to AS/400 Servlets 171 4.5.1 Enhancing the Servlet This section shows how to enhance the servlet to allow user input and to use an HTML file to control the servlet. The enhanced servlet is shown in Figure 139.
Figure 139. Enhanced Servlet
To produce the enhanced servlet, perform the following steps: 1. Add the doPost method to the PartsServlet class. 2. Create an HTML file to control running the servlet.
172 Building AS/400 Internet-Based Applications with Java public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
// set the MIME type to text/html response.setContentType("text/html"); // create the output stream ServletOutputStream out = response.getOutputStream(); try { // get the value from the input field named part (see HTML file) // and check if value is valid String[] parameter = request.getParameterValues("partno"); if (parameter[0].trim().length() == 0) parameter[0] = "*ALL"; Vector parts = null; // write the HTML header to the output stream outputHeader(out); // retrieve all data from the database parts = partsCatalog.getAll(); // process the request according to the value of the input field if (!parameter[0].toUpperCase().equals("*ALL")) { Vector selectedParts = new Vector(); Enumeration partsE = parts.elements(); while (partsE.hasMoreElements()){ domain.Part aPart = (domain.Part)partsE.nextElement(); if ((aPart.getNumber()).equals((new java.math.BigDecimal(parameter[0])))){ selectedParts.addElement(aPart); }; }; parts = selectedParts; }; // write the HTML table to the output stream outputPartsInformation(out, parts); close(out); return; } catch(Throwable e){ printError(out, e); } } // end of doPost()
Figure 140. The doPost Method
In Figure 140, we show the doPost method. We use the outputHeader, getAll, and outputPartsInformation methods in exactly the same way as in the doGet method.
We use the HttpServletRequest class getParameterValues method to read the value from the partno field. We need to define the partno field in the HTML file. If the parameter is *all, we return all parts. Otherwise, we return only the part record requested.
Notice that we use the getAll method to retrieve all the records from the database. If only one record is requested from the database, we find it in the Vector containing all the records and return only that record. Since the database is small, this does not cause a performance problem. If we actually implemented this in a production environment, we would add a getPart method, which would retrieve only one part record.
Introduction to AS/400 Servlets 173
This file uses the servlet PartsServlet to retrieve information from the AS/400
Figure 141. Servlet HTML File (Parts.html)
Figure 141 shows the source for the HTML file that we use to run the servlet. We use the FORM action tag to specify which servlet to run and the method to use. In this case, we use the POST method. We use the INPUT TYPE tag to define an input field named partno. The name we use here must match the parameter name that we use in the doPost method.
4.6 Executing the Servlet After creating the servlet, we are ready to deploy the servlet on an HTTP server. The application discussed in this chapter uses servlets to access AS/400 resources. To run it, we need a server that supports Java servlets. We tested the application using two servers: • The Domino Go Webserver running on a Windows/NT platform • The IBM HTTP Server for AS/400 running on an AS/400 system
174 Building AS/400 Internet-Based Applications with Java 4.6.1 Running under the Domino Go Webserver The Domino Go Webserver is part of the recently announced IBM WebSphere software family. It is a scalable, high-performance Web server that is available, in addition to OS/390, on many workstation platforms (AIX, Solaris, HP-UX, OS/2 Warp, Windows NT, and Windows 95).
Figure 142. Three-Tier Servlet Architecture
The Domino Go Webserver includes: • State-of-the-art security • Site indexing capabilities • Advanced server statistics reporting • Relational database connectivity with Net.Data • Support for Java servlets on all platforms • Support for JDK 1.1 • Support for the JIT (Just-in-Time) compiler • HTTP 1.1 • Web-site content rating
We use the combination of Domino Go Webserver and ServletExpress to provide a three-tier implementation for the servlet: • Client—Provides the end-user interface • NT server—Provides the HTTP server • AS/400—Provides the database server
For the Domino Go Webserver and ServletExpress, we export the classes to the \ServletExpress\servlets directory on the NT server.
To view the configuration steps for Domino Go Webserver, see Section 9.1, “Domino Go Webserver” on page 287.
Note You can run both the client and Domino Go Webserver on the same hardware platform. This allows you to test the three-tier implementation using two hardware platforms.
To export the Java classes, follow these steps: 1. In the Workbench, select the packages dataAccess, domain, and servlets. 2. From the File menu, select Export. In the dialog that follows, select only the Class Files option. 3. Ensure that the Directory radio button is selected. 4. Press the Next button. 5. In this dialog, specify the path to the x:\ServletExpress\servlets directory. Where x = a drive on the NT server. 6. Export only the class files. 7. Press the Finish button.
Introduction to AS/400 Servlets 175 4.6.1.1 Configure ServletExpress Now you are ready to configure ServletExpress. ServletExpress allows you manage the servlets running under the control of the Web server. You do not have to use ServletExpress to run servlets under the Domino Go HTTP server if they are stored in the default directory. For the PartsServlet class, it is stored in a package named servlets. When you export it, it is exported to a subdirectory named servlets in the default directory. You need to configure ServletExpress so it can find the PartsServlet class. ServletExpress also makes it easy for you to load and unload servlets without stopping the Web server. To configure ServletExpress, see Section 9.2, “ServletExpress” on page 289.
4.6.1.2 Running the PartsServlet After these configuration steps, you are ready to test your servlet. Point your Web browser to the following URL: http://server:xxxx/servlet/PartsServlet
Press the Enter key. Replace server with the name of your server and xxxx with the port you are using (by default, Domino Go uses port 0080).
If everything is configured properly, you should see the table with all the parts in it as shown in Figure 138 on page 171.
But what if not everything works as expected? Are there any means to debug or trace the program? Maybe you noticed in some of the PartsServlet's methods that the log() method is called. When you call this method, the arguments are logged on the server. This is similar to what you are normally doing when using System.out.println().
You can find the log file used by the Domino Go Webserver and ServletExpress in the directory \ServletExpress\logs\ncfservice under the name of event_log. When you open this file using NotePad, for example, you can see that there are some lines at the end that were produced by the PartsServlet class. This logging facility can be helpful when trying to find program problems.
4.6.1.3 Running the Enhanced Servlet To run the servlet using the HTML file discussed in Section 4.5.1, “Enhancing the Servlet” on page 172, in the browser, enter: http://server/apptest/Parts.html
The page shown in Figure 143 on page 177 appears. In this scenario, you can select either one specific part or all parts from the parts database.
176 Building AS/400 Internet-Based Applications with Java
Figure 143. Enhanced Servlet
4.6.2 Running under the IBM HTTP Server for AS/400 We use the combination of the IBM HTTP Server for AS/400 and the WebSphere Application Server to provide a two-tier implementation for the servlet. This support is available with OS/400 V4R3 and later. In Figure 144, client provides the end user interface and AS/400 provides the HTTP server and the database server.
Figure 144. Two-Tier Servlet Architecture
For the IBM HTTP Server for AS/400 and the WebSphere Application Server, we export the classes to the \QIBM\ProdData\IBMWebAS\servlets directory in the AS/400 Integrated File System.
To view the configuration steps for the IBM HTTP Server for AS/400, see Section 9.3, “IBM HTTP Server for AS/400” on page 293.
4.6.3 Running Servlets on the AS/400 System The IBM WebSphere Application Server is IBM's Java servlet-based Web application server that helps you deploy and manage Web applications. They range from simple Web sites to powerful e-business solutions. For detailed information on how to obtain and use the IBM WebSphere Application Server for AS/400, see the following URL: http://www.as400.ibm.com/HTTP
Introduction to AS/400 Servlets 177 You can configure a server instance of the IBM HTTP Server for AS/400 to run WebSphere. It is enabled through the Server API of the HTTP Server. For information about how to configure the IBM HTTP Server for AS/400 and the IBM WebSphere Application Server for AS/400, see Chapter 9, “HTTP Server Configuration” on page 287. For an entire listing of the IBM HTTP Server for AS/400 configuration file used for this redbook, refer to Appendix B, “IBM HTTP Server for AS400 Configuration” on page 301.
4.6.4 Running the PartsServlet Servlet on the AS/400 System Once you configure the IBM HTTP Server for AS/400 and the WebSphere application server to serve servlets, you can run the PartsServlet servlet on the AS/400 system. Enter: http://yourAS400Server:xxxx/servlet/PartsServlet
To run the servlet using the HTML file, enter: http://yourAS400Server:xxxx/apptest/Parts.html
The variable yourAS400Server is the name of your AS/400 system. The variable xxxx is equal to the TCP/IP port over which you are running the IBM HTTP Server for AS/400.
178 Building AS/400 Internet-Based Applications with Java Chapter 5. Overview of the Order Entry Application
This chapter covers an example RPG order entry application. This application represents a commercial application, although it does not include all the necessary error handling a business application requires. In Chapter 6, “Developing AS/400 Java Applets” on page 193, we convert this RPG application to a Java Internet-based application.
5.1 Overview of the Order Entry Application This section provides an overview of the application and a description of how the application database is used.
5.1.1 The ABC Company The ABC Company is a wholesale supplier with one warehouse and 10 sales districts. Each district serves 3000 customers (30000 total customers for the company). The warehouse maintains stock for the 100000 items sold by the Company. The following diagram illustrates the company structure (warehouse, district, and customer).
Figure 145. The Company Structure
5.1.2 The ABC Company Database The company runs its business with a database. This database is used in a mission critical, OLTP (online transaction processing) environment. The database includes tables with the following data: • District information (next available order number, tax rate, and so on) • Customer information (name, address, telephone number, and so on) • Order information (date, time, shipper, and so on) • Order line information (quantity, delivery date, and so on) • Item information (name, price, item ID, and so on) • Stock information (quantity in stock, warehouse ID, and so on.)
© Copyright IBM Corp. 1999 179 5.1.3 A Customer Transaction A customer transaction occurs based on the following series of events: 1. Customers telephone one of the 10 district centers to place an order. 2. The district customer service representative answers the telephone, obtains the following information, and enters it into the application: • Customer number • Item numbers of the items the customer wants to order • The quantity required for each item 3. The customer service representative may prompt for a list of customers or a list of parts. 4. The application then performs the following actions: a. Reads the customer last name, customer discount rate, and customer credit status from the Customer Table (CSTMR). b. Reads the District Table for the next available district order number. The next available district order number increases by one and is updated. c. Reads the item names, item prices, and item data for each item ordered by the customer from the Item Table (ITEM). d. Checks if the quantity of ordered items is in stock by reading the quantity in the Stock Table (STOCK). 5. When the order is accepted, the following occurs: a. Inserts a new row into the Order Table to reflect the creation of the new order (ORDERS). b. A new row is inserted into the Order Line Table to reflect each item in the order. c. The quantity is reduced by the quantity ordered. d. A message is written to a data queue to initiate order printing.
5.1.4 Application Flow The RPG Order Entry Application consists of the following components:
Note To download the sample code used in this redbook, please refer to Appendix A.1, “Downloading the Files from the Internet Web Site” on page 299, for more information.
• ORDENTD (Parts Order Entry)—Display File • ORDENTR (Parts Order Entry)—Main RPG processing program • PRTORDERP (Parts Order Entry)—Print File • PRTORDERR (Print Orders)—RPG server job • SLTCUSTD (Select Customer)—Display file • SLTCUSTR (Select Customer)—RPG SQL stored procedure • SLTPARTD (Select Part)—Display file • SLTPARTR (Select Part)—RPG stored procedure
180 Building AS/400 Internet-Based Applications with Java Figure 146. RPG Application Flow
ORDENTR is the main RPG program. It is responsible for the main line processing. It calls two supporting RPG programs that are used to prompt for and select end-user input. They are SLTCUSTR which handles selecting a customer, and SLTPARTR which handles selecting part numbers. PRTODERR is an RPG program that handles printing customer orders. It reads order records that were placed on a data queue and prints them in a background job.
5.1.5 Customer Transaction Flow The following scenario walks through a customer transaction showing the application flow. By understanding the flow of the AS/400 application, you can understand the changes made to this application to support a graphical client.
5.1.5.1 Starting the Application To start the application, the customer calls the main program from an AS/400 command line: CALL ORDENTR
When the order entry application is started, the display in Figure 147 on page 182 appears.
Overview of the Order Entry Application 181 Figure 147. Parts Order Entry
When the Parts Order Entry display appears, the user has two options: • Type in a customer number and press the Enter key • End the program by pressing either F3 or F12.
If they do not know the customer number, the user can press F4 to view a window containing a list of available customers.
182 Building AS/400 Internet-Based Applications with Java Figure 148. Select Customer
The user presses F12 to remove the window and return to the initial panel, or scrolls through the items in the list until they find the customer they want. By typing a 1 in the option field and pressing the Enter key, the user indicates their choice. The selected customer is then returned to the initial panel.
Overview of the Order Entry Application 183 Figure 149. Parts Order Entry
After selecting a customer from the list, or typing a valid customer number and pressing the Enter key, the customer details are shown and an order number is assigned. An additional prompt is displayed allowing the user to type a part number and quantity.
If the user does not know the part number, they can press F4 to view a window containing a list of available parts.
184 Building AS/400 Internet-Based Applications with Java Figure 150. Select Part
The user presses F12 to remove the window and return to the initial panel, or scrolls through the items in the list until they find the part they want. By typing a 1 in the option field and pressing the Enter key, they indicate their choice. The selected part is returned to the initial panel.
Figure 151. Parts Order Entry
Overview of the Order Entry Application 185 After selecting a customer from the list, or typing a valid customer number and pressing the Enter key, the part and quantity ordered are added to the list section below the part entry fields.
Figure 152. Parts Order Entry
The user may type a 2 beside an entry in the list to change the order. When the Enter key is pressed, a window appears that allows the order line to be changed.
Figure 153. Change Selected Order
The user chooses to press F12 to cancel the change, press F4 to list the parts, or type a new part identifier or different quantity. Pressing the Enter key validates
186 Building AS/400 Internet-Based Applications with Java the part identifier and quantity. If valid, the order line is changed in the list and the window is closed.
Figure 154. Completed Order
In Figure 154, you see the quantity for Zoo Season Pass is changed to 3. When the order is complete, the user presses F6 to update the database. Then, an order is placed on the data queue for printing.
Figure 155. Printed Order
Overview of the Order Entry Application 187 The printed order is created by a batch process. It shows the customer details and the items, quantities, and cost of the order.
5.1.6 Database Table Structure The ABC Company database has eight tables: • District • Customer • Order • Order Line • Item • Stock • Warehouse • History
The relationship among these tables are shown in Figure 156.
Figure 156. Table Relationships
5.1.7 Order Entry Application Database Layout The sample application uses the following tables of the database: • District • Customer • Order • Order line • Stock • Item (catalog)
The following sections describe, in detail, the layout of the database.
188 Building AS/400 Internet-Based Applications with Java 5.1.7.1 Tables Table 14. District Table Layout (Dstrct) Field Name Real Name Type Length
DID District ID Decimal 3
DWID Warehouse ID Character 4
DNAME District Name Character 10
DADDR1 Address Line 1 Character 20
DADDR2 Address Line 2 Character 20
DCITY City Character 20
DSTATE State Character 2
DZIP Zip Code Character 10
DTAX Tax Decimal 5
DYTD Year to Date Balance Decimal 13
DNXTOR Next Order Number Decimal 9
Primary Key: DID and DWID
Table 15. Customer Table Layout (CSTMR) Field Name Real Name Type Length
CID Customer ID Character 4
CDID District ID Decimal 3
CWID Warehouse ID Character 4
CFIRST First Name Character 16
CINIT Middle Initials Character 2
CLAST Last Name Character 16
CADDR1 Address Line 1 Character 20
CCREDT Credit Status Character 2
CADDR2 Address Line 2 Character 20
CDCT Discount Decimal 5
CCITY City Character 20
CSTATE State Character 2
CZIP Zip Code Character 10
CPHONE Phone Number Character 16
CBAL Balance Decimal 7
CCRDLM Credit Limit Decimal 7
CYTD Year to Date Decimal 13
Overview of the Order Entry Application 189 Field Name Real Name Type Length
CPAYCNT Payment Decimal 5
CDELCNT Delivery Qty Decimal 5
CLTIME Time of Last Order Numeric 6
CDATA Customer Information Character 500
Primary Key: CID, CDID, and CWID
Table 16. Order Table Layout (ORDERS) Field Name Real Name Type Length
OWID Warehouse ID Character 4
ODID District ID Decimal 3
OCID Customer ID Character 4
OID Order ID Decimal 9
OENTDT Order Date Numeric 8
OENTTM Order Time Numeric 6
OCARID Carrier Number Character 2
OLINES Number of Order Lines Decimal 3
OLOCAL Local Decimal 1
Primary Key: OWID, ODID, and OID
Table 17. Order Line Table Layout (ORDLIN)r Field Name Real Name Type Length
OID Order ID Decimal 9
ODID District ID Decimal 3
OWID Warehouse ID Character 4
OLNBR Order Line Number Decimal 3
OLSPWH Supply Warehouse Character 4
OLIID Item ID Character 6
OLQTY Quantity Ordered Numeric 3
OLAMNT Amount Numeric 7
OLDLVD Delivery Date Numeric 6
OLDSTI District Information Character 24
Primary Key: OLWID, OLDID, OLOID, and OLNBR
190 Building AS/400 Internet-Based Applications with Java Table 18. Item Table Layout (ITEM) Field Name Real Name Type Length
IID Item ID Character 6
INAME Item Name Character 24
IPRICE Price Decimal 5
IDATA Item Information Character 50
Primary Key: IID
Table 19. Stock Table Layout (Stock) Field Name Real Name Type Length
STWID Warehouse ID Character 4
STIID Item ID Character 6
STQTY Quantity in Stock Decimal 5
STDI01 District Information Character 24
STDI02 District Information Character 24
STDI03 District Information Character 24
STDI04 District Information Character 24
STDI05 District Information Character 24
STDI06 District Information Character 24
STDI07 District Information Character 24
STDI08 District Information Character 24
STDI09 District Information Character 24
STDI10 District Information Character 24
STYTD Year to Date Decimal 9
STORDERS Quantity Decimal 5
STREMORD Quantity Decimal 5
STDATA Item Information Character 50
Primary Key: STWID and STIID
5.1.8 Database Terminology This redbook concentrates on the use of the AS/400 system as a database server in a client/server environment. In some cases, we use SQL to access the AS/400 database. In other cases, we use native database access.
Overview of the Order Entry Application 191 The terminology used for the database access is different in both cases. In Table 20, you find the correspondence between the different terms. Table 20. Database Terminology AS/400 Native SQL
Library Collection
Physical File Table
Field Column
Record Row
Logical File View or Index
192 Building AS/400 Internet-Based Applications with Java Chapter 6. Developing AS/400 Java Applets
This chapter investigates a more complex applet development scenario. We build an AS/400 Internet-based shopping applet. It is actually a set of three applets. These applets use the CPW databases that are described in Chapter 5, “Overview of the Order Entry Application” on page 179. The databases are AS/400 databases and are accessed using JDBC. This suite of applets allow you to select items from the Item database, place and confirm orders, and check the status of orders. This application example is an Internet-based version of the RPG order entry application discussed in Section 5.1, “Overview of the Order Entry Application” on page 179.
The first two applets are the Toolbox applet and Cart applet. Use them to select items to order and to place an order: • Toolbox applet – Used to query the Item database and select items to be ordered • Cart applet – Used to check what items have been selected – Used to place and confirm an order for those items
Normally the Toolbox applet works in conjunction with the Cart applet. The third applet is independent of the preceding two applets. It is the Status applet and is used to check the status of an order.
Note The example programs discussed in this chapter are available for you to download from the redbook Web site. Refer to Appendix A.1, “Downloading the Files from the Internet Web Site” on page 299 for details.
6.1 Shopping Application User Interface This section shows the "shopping" applet graphical user interfaces. The images shown were captured when running under Netscape Navigator.
© Copyright IBM Corp. 1999 193 Figure 157. Toolbox Applet
Figure 157 shows the Toolbox applet, which is the first applet we investigate. It allows you to query the AS/400 Items database for information and display the query results in a listbox. You can select the items you want and put them into a “Shopping Cart.” Then, use the Cart applet to check your selected items and place an order. You can also use the Status applet to check the status of your orders.
Figure 158. Cart Applet
Figure 158 shows the Cart applet. It displays the items that you select using the Toolbox applet. Normally, the Toolbox applet and the Cart Applet are run together in a browser.
194 Building AS/400 Internet-Based Applications with Java Figure 159. Placing an Order
In the Cart applet, confirm your order by entering a valid customer number. The number entered is checked against the AS/400 Customer database. If the customer number is valid, the “Confirm Order” button is enabled as shown in Figure 159. You can place an order by clicking on the Confirm Order button.
Figure 160. Order Confirmation
Upon confirmation of the order, the Cart applet returns a message box, which displays an order number. Use the order number to track the order status.
Developing AS/400 Java Applets 195 Figure 161. Status Applet
The Order Status applet, shown in Figure 161, allows you to check the status of an order by entering the order number and clicking on the Query button.
The Shopping application has limitations that can easily be eliminated by adding additional function to the applets. These limitations include: • The Toolbox applet only allows you to order a quantity of one. • The Cart applet does not allow you to delete items from the cart.
6.2 Shopping Application Objects and Classes Figure 162 on page 197 shows the design of the Shopping application. It consists of five classes. Three of the classes are applets that provide a graphical user interface, while the other two are supporting classes. All of the programs discussed in the chapter are available for you to ownload from the redbook Web site. The "Shopping" application was created using VisualAge for Java 2.0 Enterprise Edition.
196 Building AS/400 Internet-Based Applications with Java Figure 162. Shopping Application Design
A project named “AppletWorkshop” that holds a package named ToolboxApplet and the classes is in the VisualAge for Java Integrated Development Environment(IDE). The project includes: • ToolboxApplet—A GUI applet that allows items to be selected. • CartApplet—A GUI applet that allows orders to be placed. • StatusApplet—A GUI applet that checks the order status. • ItemsDb—A supporting class that provides access to the AS/400 database (it is used by the GUI applets). • SelectedItems—A class for storing the items selected. A cart object is instantiated from this class. The GUI applets can put items into the cart or display what is in the cart.
The ItemsDb and SelectedItems classes are created to promote reusability. The other classes use them. This allows you to easily change and add functionality to the application.
Figure 163 on page 198 shows the ToolboxApplet package in the VisualAge for Java WorkBench. The runner superscript on the top right hand corner of a class means that it is a runnable Java applet.
Developing AS/400 Java Applets 197 Figure 163. ToolboxApplet Package
In addition to the classes shown in the ToolboxApplet package, we use several other classes: • The MultiColumnListbox from the IBM Enterprise Access Libraries project to display the selected items • The AS/400 Toolbox for Java classes to allow access to the AS/400 system • The Java classes in the Java Classes Library project to provide Java support • The Vector class from the java.util package to store the items in the "shopping" cart – A Vector is a collection of different objects. – The difference between a Vector and an Array is: • An array is a collection of the same type of objects. • A vector is a collection of different or the same type of objects. – VectorEnumeration is a support class: • It allows you to scroll through the entire list of objects inside a Vector. • It provides two main methods: –getNextElement() –hasmoreElements() – Elements can be of different types in a vector; you have to type cast the element to the proper type before using.
6.3 The SelectedItems Class The SelectedItems class is a supporting class used with the Toolbox applet and the Cart applet. SelectedItems acts as a buffer that stores items that you select. As you view items that are available, you can select items and place them in your “Shopping Cart.” You can view the items you select, which are stored in a SelectedItems object.
The SelectedItems class contains a static vector named wanted that contains all of the items selected. This is the “shopping cart” where we keep the selected items. It also contains a static BigDecimal variable named totalAmount that
198 Building AS/400 Internet-Based Applications with Java stores the total value of the items selected. We use the static keyword because we want other classes to share these variables.
6.3.1 Writing the Class The class definition for the SelectedItems class is shown in Figure 164.
import java.math.BigDecimal; import java.util.Vector; public class SelectedItems { private static Vector wanted; public static BigDecimal totalAmount; }
Figure 164. SelectedItems Class Definition
The two import statements tell the compiler where the supporting classes are located. The BigDecimal class is in the java.math package. The Vector class is in the java.util package.
In some cases, generic import statements are used. Instead of writing “import java.math.BigDecimal;” we can write “import java.math.*”, so that all classes in the java.math package are known to the compiler.
The advantage of using the specific import statement rather than the generic one is that specific import statements document exactly what additional classes are used in the application. This facilitates modifying code and packaging the application using JAR files.
6.3.2 Writing the Methods First, we discuss the getVector method which allows other classes or methods to access the Vector named wanted (we declare this name as private). Declaring a variable as private gives the class owner more control over it because other users cannot access it directly. They can only access it through owner-supplied public methods. Here, we supply the public getVector method. Also, if the wanted Vector is not instantiated, we instantiate it here. This is called lazy initialization so if the Vector is disposed later, it is regenerated when needed.
public Vector getVector() { if (wanted == null) wanted = new Vector(); return wanted; }
Figure 165. The getVector Method
The clear method allows other applets to clear the cart and remove selections from the cart.
Developing AS/400 Java Applets 199 public void clear() { wanted = null; }
Figure 166. The clear Method
Finally, the addSelectedRows method allows items to be added to the wanted Vector that was previously created. An object array is used as the input parameter.
We add the object array to the vector and add the price of the item to the totalAmount variable. Because we may not have initialized the totalAmount variable, we set it to zero if it is empty.
public void addSelectedRow(Object[] row) { getVector().addElement(row); if (totalAmount == null) { totalAmount = new BigDecimal("0"); } String Column3 = new java.lang.String((String) row[2]); totalAmount = totalAmount.add(new BigDecimal(Column3.trim())); }
Figure 167. The addSelectedRow Method
6.4 The ItemsDb Class The ItemsDb class is a supporting class that provides access to the AS/400 system. All the graphical user interface applets use this class to access the AS/400 databases. The class definition is shown in Figure 168 on page 201.
200 Building AS/400 Internet-Based Applications with Java import java.math.*; import java.util.*; public class ItemsDb extends java.lang.Object { private java.sql.Connection dbConnect; private java.sql.PreparedStatement psItem; private java.sql.PreparedStatement psItemRange; private java.sql.PreparedStatement psCustomerDb; private java.sql.PreparedStatement psQuantityInHand; private java.sql.Statement sGetInetOrderNo; private String systemName = new String(""); private String userid = new String(""); private String password = new String(""); private java.sql.ResultSet rs = null; public String itemId; public String itemName; public BigDecimal itemPriceBigDecimal; public String itemPrice; public String itemInfo; public Object[] row; public String validCustomerId = null; protected java.util.Vector aConnectionListener = null; }
Figure 168. The ItemsDb Class Definition
The class definition declares all the variables that we use in this class. An explanation of the variables is shown in Table 21 on page 202.
Developing AS/400 Java Applets 201 Table 21. ItemsDb Class Variables
6.4.1 Common Methods All Applets Use The ItemsDb class provides some methods that are used by all GUI applets.
6.4.1.1 The connect Method The connect method is used to connect to the AS/400 system. It uses the system name, user ID, and password defined in the class variables. It also prepares the JDBC statements that are used to access the AS/400 databases.
202 Building AS/400 Internet-Based Applications with Java public String connect() { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalConnect"); java.sql.DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver()); dbConnect = java.sql.DriverManager.getConnection("jdbc:as400://" + systemName + "/apilib;naming=system;errors=full;date format=iso", userid, password); psItem = dbConnect.prepareStatement("SELECT * FROM apilib/ITEM WHERE IID = ?"); psItemRange = dbConnect.prepareStatement("SELECT * FROM apilib/ITEM WHERE IID >= ? AND IID <= ?"); psCustomerDb = dbConnect.prepareStatement("SELECT CID FROM apilib/CSTMR WHERE CID = ? AND CDID=001 AND CWID='0001'"); psQuantityInHand = dbConnect.prepareStatement("SELECT STQTY FROM apilib/STOCK WHERE STWID= '0001' AND STIID=?"); } catch (Exception e) { System.out.println("connect(): " + e); e.printStackTrace(); return "Connect: " + e; } return "Connect Successfully"; }
Figure 169. The connect Method
If we load an applet from the local workstation disk, we must handle security. By default, applets do not have access to any remote system. In this case, the AS/400 system is a remote system. Here, we run under Netscape Navigator, so we use the security support provided by Netscape. We use the enablePriviledge method from the PrivilegeManger class. This causes a security dialog to appear when we attempt to connect to the AS/400 system. If we use the AS/400 HTTP server to serve the applets, we automatically have access to the AS/400 system, so we do not need to provide any special security support. For more information about security and deploying applets, refer to Chapter 3, “Introduction to AS/400 Applets” on page 51.
6.4.1.2 The disconnect Method The disconnect method is used for closing all AS/400 connections.
public void disconnect() throws Exception { dbConnect.close(); psItem.close(); psItemRange.close(); psCustomerDb.close(); psQuantityInHand.close(); return; }
Figure 170. The disconnect Method
6.4.1.3 The finalize Method The finalize method automates using the disconnect method. Every time the ItemsDb class is disposed, it disconnects from the AS/400 system and releases all resources allocated.
Developing AS/400 Java Applets 203 protected void finalize() { try { disconnect(); super.finalize(); } catch (Throwable t) { System.out.println(t); } return; }
Figure 171. The finalize Method
6.4.2 Methods Used by the Toolbox Applet The ItemsDb class has some methods that are used only by the Toolbox applet class.
6.4.2.1 The fetchNextItem Method The fetchNextItem method is used after executing a JDBC statement that returns a resultset. It fetches the next record from the current resultset and puts the corresponding field values in the public class variables. It returns itself (this) to allow for the cascading of methods.
204 Building AS/400 Internet-Based Applications with Java public ItemsDb fetchNextItem() { try { if (rs.next()) { itemId = rs.getString("IID"); itemName = rs.getString("INAME"); itemPriceBigDecimal = rs.getBigDecimal("IPRICE", 2); itemPrice = itemPriceBigDecimal.toString(); itemInfo = rs.getString("IDATA"); } else { itemId = null; itemName = null; itemPriceBigDecimal = null; itemPrice = null; itemInfo = null; } } catch (Exception e) { System.out.println("fetchnext fail: " + e); } return this; }
Figure 172. The fetchNextItem Method
6.4.2.2 The getItem Method The getItem method queries the ITEM table using the itemno parameter passed to it as input. It executes the psItem prepared statement object that was prepared in the connect method. It uses the fetchNextItem method to load the information from the resultset into the class variables.
public ItemsDb getItem(String itemno) { try { psItem.setString(1, itemno); rs = psItem.executeQuery(); fetchNextItem(); } catch (Exception e) { System.out.println("getItem fail: " + e); } return this; }
Figure 173. The getItem Method
Developing AS/400 Java Applets 205 6.4.2.3 The getItems Method The getItems method queries the ITEM database for items matching a range of item numbers. It executes the psItemRange prepared statement object created in the connect method. It uses the fetchNextItem method to load the data into the class variables. If there are no more records, the class variables are set to null.
public java.sql.ResultSet getItems(String itemnoMin, String itemnoMax) { if (itemnoMax.length() == 0) { getItem(itemnoMin); } else { try { psItemRange.setString(1, itemnoMin); psItemRange.setString(2, itemnoMax); rs = psItemRange.executeQuery(); } catch (Exception e) { System.out.println("getItemS fail: " + e); } } return rs; }
Figure 174. The getItems Method
6.4.3 Methods Used by CartApplet The ItemsDb class provides some methods that are only used by the Cart applet.
6.4.3.1 The quantityInHand Method The quantityInHand method returns the Quantity in Stock value for an item from the AS/400 Stock table. It executes the psQuantityInHand prepared statement object that was prepared in the connect method.
206 Building AS/400 Internet-Based Applications with Java public BigDecimal quantityInHand(String itemNo) { try { // Get next Order No. and the Inet YTD Balance psQuantityInHand.setString(1, itemNo); rs = psQuantityInHand.executeQuery(); rs.next(); return rs.getBigDecimal("STQTY", 0); } catch (Exception e) { System.out.println(e); } return null; }
Figure 175. The quantityInHand Method
6.4.3.2 The verifyCustomer Method The verifyCustomer method checks whether the customerId passed as an input parameter is valid. It executes the psCustomerDb prepared statement object created in the connect method. It returns as true or false depending on the result of the check. If the customerId is valid, it saves it in the class variable validCustomerId.
public boolean verifyCustomer(String customerId) { boolean isvalid = false; try { psCustomerDb.setString(1, customerId); rs = psCustomerDb.executeQuery(); if (rs.next()) { isvalid = true; validCustomerId = customerId; } } catch (Exception e) { validCustomerId = null; } return isvalid; }
Figure 176. The verifyCustomer Method
6.4.3.3 The confirmOrder Method The confirmOrder method creates an order from the items inside the SelectedItems object. The customerId is validated by the verifyCustomer method prior to confirming the order.
Developing AS/400 Java Applets 207 The confirmOrder method uses JDBC to access the AS/400 database. It contains the following logic: • Verify if there are items in the cart. • Retrieve the next order number and district YTD balance from the AS/400 District table. • Update the District YTD balance with the new order total. • Increment the District next order number by one. • Insert an order record to the AS/400 Order table. • Update the stock balance in the AS/400 Stock table. • Insert an order line record in the AS/400 Order Line table for each item ordered. • Return the order number used. • Clear the items from the cart.
When confirming the order, the confirmOrder method performs the following actions: • Retrieves the next order number DNXTOR from the District table(DSTRCT) • Increments it by one • Writes it back to the District table
6.4.4 Methods Used by the StatusApplet The ItemsDb class provides some methods that are used only by the Status applet.
6.4.4.1 The checkOrderStatus Method The checkOrderStatus method receives an order number as a parameter, which it uses to query the AS/400 database for order information. It returns a Vector named orderStatus which contains all the details about the order.
208 Building AS/400 Internet-Based Applications with Java public Vector checkOrderStatus(String orderIdString) { // return Vector contains CustomerLastName, CustomerFirstName,Object[],Object[],... // where Object[] is OrderLineDetail => [ItemId,ItemName,QtyOrdered,Amount] Vector orderStatus = new Vector(); if (orderIdString.length() > 9 || orderIdString.length() == 0) return null; try { sGetInetOrderNo = dbConnect.createStatement(); rs = sGetInetOrderNo.executeQuery("SELECT OCID,OLINES FROM ORDERS WHERE OWID='0001' AND ODID=001 AND OID=" + orderIdString); rs.next(); String customerId = rs.getString("OCID"); BigDecimal orderLines = rs.getBigDecimal("OLINES", 0); rs = sGetInetOrderNo.executeQuery("SELECT CFIRST,CLAST FROM CSTMR WHERE CWID='0001' AND CDID=001 AND CID='" + customerId + "'"); rs.next(); String lastName = rs.getString("CLAST"); String firstName = rs.getString("CFIRST"); orderStatus.addElement(lastName); orderStatus.addElement(firstName); . . . return orderStatus; }
Figure 177. The checkOrderStatus Method
6.5 The Toolbox Applet This applet allows you to enter a system name, user ID and password, and connect to the AS/400 system. If the connection is successful, the QueryRange of Items button is enabled. You can click on the Query Range of Items button to get the items found in the ITEM table for the range specified by TextField1 and TextField2. The item information is displayed in the listbox. It uses the ItemsDb class for all the AS/400 Database accesses.
6.5.0.1 Basic Class Definition Figure 178 shows the basic class structure, class variables, and the multicolumn listbox declaration.
import java.applet.*; import java.awt.*; import java.net.URL; import java.util.*; public class ToolboxAppletExample extends Applet implements java.awt.event.ActionListener, java.awt.event.ItemListener { static SelectedItems selected = new SelectedItems(); private com.ibm.ivj.eab.dab.IMulticolumnListbox ivjIMulticolumnListbox1 = null; private java.sql.DriverManager ivjDriverManager1 = null; }
Figure 178. ToolboxAppletExample Class Definition
Developing AS/400 Java Applets 209 We declare a variable named selected, which is based on the SelectedItems class. Because selected is declared as static, it is shared by all other classes that declare it. We declare a multicolumn listbox named ivjIMulticolumnListbox1. It is based on the IMulticolumnListbox class from the com.ibm.eab.dab package, which is included with VisualAge for Java Enterprise Edition. We declare a DriverManager, which is used for the JDBC connection.
6.5.1 The addAllRows Method The addAllRows method is called after a JDBC statement that returns a resultset is executed. It uses the fetchNextItem method to loop through the resultset and retrieve all returned items. It formats the item information into an array, which is used to populate the listbox.
public void addAllRows(ToolboxApplet.ItemsDb anItemDb) { anItemDb.fetchNextItem(); while (anItemDb.itemId != null) { String[] array = new String[4]; array[0] = anItemDb.itemId; array[1] = anItemDb.itemName; array[2] = insertSpaces(anItemDb.itemPrice, 6); array[3] = anItemDb.itemInfo; getIMulticolumnListbox1().addRow(array, array[0]); anItemDb.fetchNextItem(); } }
Figure 179. The AddAllRows Method
6.5.2 The getSelectedIndexes Method The getSelectedIndexes method is called when the user clicks on the Put Selection into Cart button. It determines which listbox indexes are selected. It adds the selected rows of the listbox to the SelectedItems class object named selected. It places the selected items into the “cart.”
public void getSelectedIndexes() { Object key = getIMulticolumnListbox1().getSelectedObject(); selected.addSelectedRow(getIMulticolumnListbox1().getRowData(key)); }
Figure 180. The getSelectedIndexes Method
6.5.3 Checking the Connections Figure 181 on page 211 shows the Toolbox applet in the VisualAge for Java Visual Composition Editor(VCE).
210 Building AS/400 Internet-Based Applications with Java removeAllRows
getItems addAllRows enabled
getSelectedIndexes
connect
Figure 181. Toolbox Applet in the VCE
We use the following connections in this applet: • connect button: – ItemsDb—setSystemName method – ItemsDb—setUserID method – ItemsDb—setPassword method – ItemsDb—connect method • Connect the normal result to the message label • Connect the normal result to enable the Query Range of Items button • Query Range of Items button: – ToolboxAppletExample—removeAllRows method to clear the list box – ItemsDb—getItems method to retrieve the items from the AS/400 ITEM table – ToolboxAppletExample—addAllRows method to add the items to the listbox • Put selections in cart button: – ToolboxAppletExample—getSelectedIndexes method to add the row selected in the listbox to the cart vector
6.6 The Cart Applet This applet allows you to enter a system name, user ID and password, and then connect to the AS/400 system. If the connection is successful, the Look into Cart button is enabled. You can click on the Look into Cart button to display the items currently in the shopping cart, in the listbox. You can place an order for the items in the cart by entering a valid cutomer number in the customer number text field. The number entered is validated against the AS/400 Customer table. If the
Developing AS/400 Java Applets 211 customer number is valid, the Confirm Order button is enabled. Clicking on the Confirm Order button generates an order. The created order number is returned in a message box. This class uses the ItemsDb class for all AS/400 Database accesses.
In the design of the Cart applet, we use a “Look into Cart” button to refresh the listbox. We can also implement an event for the automatic refresh of the cart whenever an item is put into the cart. For simplicity, we choose to implement the Look into Cart button.
6.6.1 Writing the Class In the class definition, we instantiate a SelectedItems object and name it cart. This variable is shared with the Toolbox applet. The Toolbox applet puts items into the cart. The Cart applet allows us to view what is in the cart and create an order for the items in the cart.
import java.applet.*; import java.awt.*; import java.util.*; public class CartApplet extends Applet implements java.awt.event.ActionListener, java.awt.event.KeyListener { SelectedItems cart = new SelectedItems(); }
Figure 182. CartApplet Class Definition
6.6.2 Viewing the Methods The showCart method is used to display what is in the cart Vector in the listbox. We use an object array of five elements (Object[5]) to store the elements from the cart Vector. The cart Vector has four objects (columns) in it: • Item Identification • Item Name • Item Price • Item Detail
We display the four values from the cart Vector, plus the Quantity in stock for the item in the listbox. We use the listbox addRow method to add rows to the listbox. It requires an array as an input parameter. We populate the array with the values from the cart Vector.
We insert the quantity in stock of the item, which we retrieve from the AS/400 system in the fourth element (Object[3]) of the array. We obtain the quantity in stock by calling the quantityInHand method in the ItemsDb class. We convert it to a String value for display.
Finally, we add the object array as a row to the listbox, display the total amount in the Total Amount TextField, and display the listbox.
212 Building AS/400 Internet-Based Applications with Java public void showCart() { try { if (cart.getVector() != null) { Enumeration enum = cart.getVector().elements(); while (enum.hasMoreElements()) { String myObject[] = new String[5]; Object[] element = ((Object[]) enum.nextElement()); myObject[0] = (String) element[0]; //ItemId myObject[1] = (String) element[1]; //ItemName myObject[2] = (String) element[2]; //Price //[3] is qty in stock. myObject[3] = (String) (getItemsDb().quantityInHand(((String) element[0]))).toString(); myObject[4] = (String) element[3]; //Details getIMulticolumnListbox1().addRow(myObject, myObject[0]); } getTextField3().setText(cart.totalAmount.toString()); return; } } catch (Exception e) { e.printStackTrace(); System.out.println(e); } return; }
Figure 183. The showCart Method
Developing AS/400 Java Applets 213 6.6.2.1 Viewing the Connections Figure 184 shows the Cart applet in the VisualAge for Java Visual Composition Editor.
removeAllRows confirmOrder
enabled showCart verifyCustomer
connect
Figure 184. The Cart Applet in the VCE
We use the following connections: • connect button: – ItemsDb—setSystemName method – ItemsDb—setUserID method – ItemsDb—setPassword method – ItemsDb—connect method • Connect the normal result to the message label • Connect the normal result to enable the Look into Cart button • Look into Cart button: – CartApplet—removeAllRows method to clear the listbox – CartApplet—showCart method to display the items in the cart Vector • Validate Customer Number: We validate the customer number field so that the Confirm Order button is only enabled if the customer number is valid. We use the verifyCustomer method in the ItemsDb class to validate it. We connect it with the KeyReleased event of the Customer Number Entry Field and the Confirm Order button. It enables the Confirm Order button if the customer number in Entry Field is found in the Database. • Confrim Order button: – ItemsDb—confirmOrder method, with the cart as the input parameter. The normal result is connected to the MessageBox's show method to display the order number.
214 Building AS/400 Internet-Based Applications with Java – CartApplet—clear method. After confirming the order, items in the list box are cleared.
6.7 The Order Status Applet The OrderStatus applet allows you to enter a system name, user ID, and password and connect to the AS/400 system. If a connection to the AS/400 system is successfully made, the Query button is enabled. You can then enter an order number and click on the Query button to check on the status of an order. This class uses the ItemsDb class for all of the AS/400 Database accesses.
public class OrderStatus extends Applet implements java.awt.event.ActionListener { private com.ibm.ivj.eab.dab.IMulticolumnListbox ivjIMulticolumnListbox1 = null; private com.ibm.ivj.eab.dab.IMessageBox ivjIMessageBox1 = null; }
Figure 185. OrderStatus Class Definition
We declare a multicolumn listbox named ivjIMulticolumnListbox1 and a message box named ivjMessageBox1. They are based on classes from the com.ibm.eab.dab package, which is included with VisualAge for Java Enterprise Edition.
To implement the Check Order Status Applet, two user-written methods are used. The fillListbox method calls the ItemsDb class checkOrderStatus method with OrderId as a parameter. The checkOrderStatus method returns a vector that contains lastname, firstname, and an array of order detail. If the order is found, the items ordered are displayed in the listbox.
Developing AS/400 Java Applets 215 public void fillListbox(String OrderId) { Vector orderStatus = getItemsDb().checkOrderStatus(OrderId); if (orderStatus == null) { getLabel2().setText("Order No. " + OrderId + " Not Found !!!"); return; } Enumeration detailLine = orderStatus.elements(); String lastName = ((String) detailLine.nextElement()); String firstName = ((String) detailLine.nextElement()); getLabel2().setText("Order " + OrderId + " was Ordered by " + firstName + " " + lastName); while (detailLine.hasMoreElements()) { String[] detail = ((String[]) detailLine.nextElement());
getIMulticolumnListbox1().addRow(detail, detail[0]); }
return; }
Figure 186. The fillListbox Method
6.7.0.1 Viewing the Connections In Figure 187 on page 216, we show the Order Status applet in the VisualAge for Java Visual Composition Editor.
connect fillListbox enabled
showException showException
Figure 187. Order Status Applet
216 Building AS/400 Internet-Based Applications with Java We use the following connections: • connect button – ItemsDb—setSystemName method – ItemsDb—setUserID method – ItemsDb—setPassword method – ItemsDb—connect method • Connect the normal result to the message label • Connect the normal result to enable the Query button • Query button: – OrderStatus—fillListbox method to retrieve and display the order information for the order number in the TextField.
6.8 Testing the Applets You can run the Toolbox applet and the Status applet inside the VisualAge for Java Integrated Development Environment. The Cart applet must be exported and run outside the IDE. We use Netscape Navigator to test outside the IDE.
To run the applets outside the VisualAge for Java IDE, we export the applet classes. We use C:\apptest as the directory in this example. We export the following classes to the apptest directory: • ToolboxAppletExample • CartApplet • StatusApplet • ItemsDb • SelectedItems
The package in which the classes are stored becomes a subdirectory of the directory to which the export is done. In this case, ToolboxApplet becomes a subdirectory of apptest.
Figure 188. The apptest\ToolboxApplet Directory
We use html files to control running the applets. The html files refer to the applet class files using the APPLET tag. An applet viewer or browser tries to find the classes in the current directory from where the html file is loaded.
Developing AS/400 Java Applets 217 Place the AS/400 Toolbox classes and any third party classes under the current directory. A jar file can also be used to hold classes. We use a jar file, named jt400.jar, to hold the AS/400 Toolbox for Java classes.
In addition to the AS/400 Toolbox for Java classes, we also need several classes from the IBM Enterprise Access libraries. We export these classes to the com subdirectory of the apptest directory. We also export the classes from the netscape.security package to provide security support. Figure 189 shows the contents of the apptest directory.
Figure 189. The apptest Directory
Running Java applets is different than running Java applications. Java applications normally use the CLASSPATH environment variable to find classes that are located locally on the workstation. In many cases, applets are loaded from a remote resource. We assume that the browser or applet viewer does not use the local disk to find supporting classes. We must make them available so they can be found. Three html files (Table 22) are available to run the applets. Table 22. Applet HTML Files
All of the html files point to the class files in the apptest directory. Figure 190 on page 219 shows the html file for Order.htm, which runs both the Toolbox applet and Cart applet under the same browser session.
218 Building AS/400 Internet-Based Applications with Java HTML>
Figure 190. Order.htm
Figure 191 shows the html file for Order1.htm which runs only the Toolbox applet.
Figure 191. Order1.htm
Figure 192 shows the html file for the Status applet.
Figure 192. Status.htm
6.9 Serving the Applets from the AS/400 System We can also run the applets by using the AS/400 HTTP server. This involves three steps: 1. Copy the apptest directory to the AS/400 system Integrated File System. 2. Configure the AS/400 HTTP server to allow the html files in apptest to be executed. Add the following directive to the HTTP configuration: Pass /apptest/* /apptest/* 3. Point the browser to the html files stored on the AS/400 system.
Developing AS/400 Java Applets 219 Refer to Section 9.3, “IBM HTTP Server for AS/400” on page 293, for information about configuring the AS/400 HTTP server.
Figure 193 shows the shopping applet running under Netscape Navigator and serving it from the IBM HTTP Server for AS/400.
Figure 193. Shopping Applet Running under Netscape Navigator
220 Building AS/400 Internet-Based Applications with Java Chapter 7. Developing AS/400 Java Servlets
In this chapter, we build a more complex servlet example. This application demonstrates building Java programs that: • Run as servlets • Run as applets • Provide security password validation and protection • Use AS/400 Toolbox for Java classes to access AS/400 resources • Run on a Windows/NT platform under Domino Go Webserver • Run on the AS/400 platform under the IBM HTTP Server for AS/400
Note The example programs discussed in this chapter are available for you to download from the redbook Web site. Refer to Appendix A.1, “Downloading the Files from the Internet Web Site” on page 299, for details.
This application runs under the control of a Web browser. The application displays shown in this chapter use the Microsoft Internet Explorer 4.0 browser. This application was also tested using Netscape Navigator 4.x.
To start the application, enter the URL of the application server. For example, to run it on an AS/400 system running the IBM HTTP Server for AS/400 and the WebSphere Application Server in the browser, enter: http://AS400ABC:xxxx/servlet/Signon
Note In this application, we pass information across the network that we may want to protect. For example, we pass in a password. In this case, we may want to use the IBM HTTP Server for AS/400 Secure Sockets Layer (SSL) support. For infomation about how to install and use SSL support on the AS/400 system, see Chapter 8, “Security Considerations” on page 261. When running the application under SSL, we enter: https://AS400ABC:xxxx/servlet/Signon
AS400ABC is the name of the AS/400 system. xxxx is the TCP/IP port over which the IBM HTTP Server for AS/400 is running. Signon is a Java program, which handles security, and runs as a Java servlet.
You can also run this application under the control of other HTTP servers. For example, you can run under the Domino Go Webserver. In this case, we use a three-tier approach: 1. The client workstation running a browser 2. The HTTP server running a server, for example Windows/NT 3. The AS/400 system
To run the application, enter: http://server:xxxx/servlet/Signon
© Copyright IBM Corp. 1999 221 In this case, server is the name of an HTTP server, which supports running servlets. We tested using Domino Go Webserver and ServletExpress running on a Windows/NT platform.
7.1 Running the Application When the application is started, the AS/400 Sign On window appears as shown in Figure 194.
Figure 194. Servlet Sign On Window
The Sign On window allows you to enter security information and sign on to the AS/400 system. After you enter a user ID, password, and AS/400 system name, click on the Signon button. The information entered is validated. A Java program running as a servlet does the validation using AS/400 Toolbox for Java classes. If the information is valid and the AS/400 system is available, the application menu window shown in Figure 195 on page 223 appears.
222 Building AS/400 Internet-Based Applications with Java Figure 195. Servlet Application Menu Window
The application menu window allows you to select an application to run. Do this by clicking the mouse pointer on the option. If you select the Database query option, the Query Recall window appears as shown in Figure 196 on page 224.
Developing AS/400 Java Servlets 223 Figure 196. Query Recall Window
The Query Recall window allows you to recall a previous query or build a new query. To build a new query, highlight new query, and click on the Open button. This displays the Query Builder window, as shown in Figure 197.
Figure 197. Query Builder Window
224 Building AS/400 Internet-Based Applications with Java The Query Builder Screen allows you to enter an SQL statement and run it on the AS/400 system. For example, to retrieve all rows from the Parts table in the apilib library, enter: select * from from apilib.parts
Clicking on the Query button causes the SQL statement to run on the AS/400 system. The results appear in a table as shown in Figure 198.
Figure 198. Query Results
Rather than writing an SQL statement, click on the Wizard button and allow the Query Wizard to help you build the SQL statement that you want to run. The Query Wizard prompts you for the name of the table that you want to use. Click on the Browse button to display the available tables or enter the name of the table, as shown in Figure 199 on page 226.
Developing AS/400 Java Servlets 225 Figure 199. Query Wizard Table Prompt
After a table name is entered, click on the Next button. The Select Fields prompt window appears as shown in Figure 200.
Figure 200. Select Fields Prompt Window
226 Building AS/400 Internet-Based Applications with Java The Select Fields window allows you to select which fields you want to include in the query. To select a field, highlight it and click on the Add button. In this example, we select the PARTNO, PARTQY, and PARTPR fields. After selecting the fields you require, click on the Next button to display the Select Conditions window shown in Figure 201.
Figure 201. Select Conditions Prompt Window
The Select Conditions prompt allows you to add conditions to the SQL statement. For example, to select only those records that have a PARTQY value of greater than 50, perform the following steps: 1. Highlight the PARTQY field. 2. Select ">" from the choice box. 3. Enter 50 in the TextField.
After setting the conditions, click on the Next button to display the Select Order prompt window shown in Figure 202 on page 228.
Developing AS/400 Java Servlets 227 Figure 202. Select Order Prompt Window
The Select Order screen allows you to add ordering information to the SQL statement. For example, to order the records based on the PARTQY field in ascending order, perform these steps: 1. Highlight the PARTQY field. 2. Click on the Ascending button.
Click on the Finish button to see the SQL statement so you can run it. Figure 203 on page 229 shows the SQL statement and the results of running it.
228 Building AS/400 Internet-Based Applications with Java Figure 203. Query Results
The second option on the application menu shown in Figure 195 on page 223, allows you to manage print jobs by user. Selecting this option displays the User ID Prompt shown in Figure 204 on page 230.
Developing AS/400 Java Servlets 229 Figure 204. User ID Prompt
Enter a valid user ID to view all the print jobs available for the user as shown in Figure 205.
Figure 205. Print Jobs By User
The Print Jobs window allows you to hold the print job, release it, or delete it from the output queue.
You can also work with print jobs by output queue. Select Manage print jobs by output queue to view the AS/400 Output Queues as shown in Figure 206 on page 231.
230 Building AS/400 Internet-Based Applications with Java Figure 206. Output Queues Display
Click on an output queue to view the print jobs in that particular output queue as shown in Figure 207.
Figure 207. Print Jobs By Output Queue
The Print Jobs window allows you to select a job and hold it, release it, or delete it from the output queue.
The Files option on the Application menu allows you to list the directories in the AS/400 integrated file system. Figure 208 on page 232 shows a directory listing for the root of the AS/400 integrated file system.
Developing AS/400 Java Servlets 231 Figure 208. AS/400 Integrated File System Directories
Select and click on one of the directories listed to view the files stored in that directory. Click on the apptest directory to view the contents of that directory as shown in Figure 209.
Figure 209. Directory Listing
Selecting System Performance from the application menu retrieves and displays AS/400 system performance information as shown in Figure 210 on page 233.
232 Building AS/400 Internet-Based Applications with Java Figure 210. AS/400 Performance Information
The Command line option allows you to enter an AS/400 command as shown in Figure 211.
Figure 211. AS/400 Command
If you enter a valid AS/400 command, for example: wrksyssts
The command runs on the AS/400 system, and the command output is written to an AS/400 print file. You are notified that a print file is created as shown in Figure 212 on page 234.
Developing AS/400 Java Servlets 233 Figure 212. AS/400 Command Output
The Change password option allows you to change your password on the AS/400 system. Selecting this options displays the screen shown in Figure 213.
Figure 213. Change Password
The final option is the Sign off option. Selecting it signs you on the AS/400 system and displays the initial sign on menu.
7.2 Application Programs This section covers the Java programs that support this application. This application consists of a number of Java classes. They are supporting class, servlets, and applets. We cover some of the key classes here to give you an understanding of how the application works. The entire application is available for you to download from our Web site.
234 Building AS/400 Internet-Based Applications with Java Note If you load the servlets that make up this application into the VisualAge for Java 2.0 Integrated Development environment, some of the classes are marked with a warning message. If you read the warning messages, they indicate that the getParameter method is deprecated. However, the Java Servlet API specification (version 2.1a, November 1998), shows this to be a supported method. Originally, Sun decided to deprecate this method, but has since reconsidered.
7.2.1 How the Application Works This application works by using HTML to display windows in a browser and reading input requests from the HTML screens. The Java programs build the HTML files "on the fly." There are no HTML source files used. Access to the AS/400 system is done through classes provided by the AS/400 Toolbox for Java.
The Signon class is a servlet that provides support for signing on to the application. It provides the following support: • Display initial sign on menu • Validate sign on information • Display application main menu
Two methods are provided to allow a servlet to interface with a client: • doGet • doPost
Each of these methods has two parameters that are passed in: • ServletRequest that encapsulates the request to the servlet • ServletResponse that encapsulates the response from the servlet
Using the ServletRequest interface or its subclass HttpServletRequest, servlets can access protocol-specific header information such as the scheme of the URL used in the request or the value of the specified parameters. After retrieving the data from the HttpServletRequest, the servlet performs the requested task and sends the information back to the client using the ServletResponse object. It allows the servlet to set the MIME content type and a Writer, through which the servlet can pass the information back to the client.
The Signon servlet is run from a browser by entering: http://server:xxxx/servlet/Signon
Entering this command from the browser runs the doGet method of the Signon class.
Developing AS/400 Java Servlets 235 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { log("Signon: doGet: Entered."); String urlStr = new String(HttpUtils.getRequestURL(req)); ServletOutputStream out = res.getOutputStream(); imgBase = "http://" + req.getServerName() + ":" + Integer.toString(req.getServerPort()) + "/"; ServletCallLog.logCaller(req, res); Enumeration e = req.getParameterNames(); if (!e.hasMoreElements()) { // a GET request came in with no parameters - // Generate a signon form genSignonForm(out, new String(HttpUtils.getRequestURL(req))); } else { String sysName = req.getParameter("system"); String userId = req.getParameter("user"); String urlBase = urlStr.substring(0, urlStr.lastIndexOf("/") + 1); String cmd = req.getParameter("cmd"); if (cmd.equalsIgnoreCase("menu")) { genMenu(out, urlBase, sysName, userId); } else if (cmd.equalsIgnoreCase("signoff")) { signOff(req, res); } else { genInfo(out, imgBase, sysName, userId); } } out.close(); }
Figure 214. SignOn doGet Method
To help you understand the processing that takes place, we added logging to the SignOn class. The log for the sign on processing shows the following entries. • Signon: Signon: doGet: Entered. The first time the doGet method is called, no parameters are passed in. It calls the genSignonForm method to generate and display the Sign on menu. • Signon: Signon: genSignonForm: Entered. The genSignonForm method shown in Figure 215, builds the Sign on menu using HTML tags. It specifies that the Post method be used and the Signon program called.
236 Building AS/400 Internet-Based Applications with Java private void genSignonForm(ServletOutputStream out, String urlBase) throws IOException { log("Signon: genSignonForm: Entered."); log("Signon: genSignonForm: imgBase = " + imgBase); String host = getHostFromURL(urlBase); out.println("
"); out.println("
out.println("
"); out.println("
Welcome to " + host); out.println("
Please log in:"); out.print("
");out.println("
out.println("");
}
Figure 215. SignOn genSignonForm Method
The urlBase variable, contains the name of the program to run. This causes the Sign on menu shown in Figure 194 on page 222 to be displayed. The HTML code that is generated by the genSignonForm method is shown in Figure 216 on page 238.
Developing AS/400 Java Servlets 237
Welcome to LOCALHOST
Please log in:
Figure 216. Generated Sign On HTML
Two key points to notice about the HTML file are: • The FORM ACTION tag specifies that the Signon servlet will be run using the Post method. • The INPUT TYPE tag specifies that clicking on a Signon button causes the servlet to run.
After the Signon button is clicked, the doPost method of the SignOn class is called: • Signon: Signon: doPost: Entered. This method calls the addUserToCache method in the SuperServlet class, which tries to create an as400 object using the sign on information. If this is successful, the user is valid and the main application window appears.
238 Building AS/400 Internet-Based Applications with Java public void doPost (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { log("Signon: doPost: Entered."); ServletCallLog.logCaller(req, res);
String sysName = req.getParameter("system"); String userId = req.getParameter("user"); String password = req.getParameter("pw");
String urlStr = new String(HttpUtils.getRequestURL(req)); String urlBase = urlStr.substring(0, urlStr.lastIndexOf("/") + 1); log("urlBase = " + urlBase);
ServletOutputStream out = res.getOutputStream();
// set content type and other response header fields first res.setContentType("text/html");
try { addUsertoCache(req, res, sysName, userId, password);
genMain(out, urlBase, sysName, userId); } catch (Exception e) { out.println("
");
out.println("
Signon to AS/400 failed"); out.println("
" + e.getMessage()); out.println("");
e.printStackTrace(); }
// then write the data of the response out.close(); }
Figure 217. SignOn doPost Method
• Signon: urlBase = http://localhost/servlet/ • Signon: Signon: genMain: Entered. After a successful sign on, the genMain method displays the main application menu and the information menu shown in Figure 195 on page 223.
Developing AS/400 Java Servlets 239 private void genMain(ServletOutputStream out, String urlBase, String sysName, String userId) throws IOException { log("Signon: genMain: Entered."); out.println(""); out.println("
"); out.println("out.println("
"); out.println(""); }Figure 218. SignOn genMain Method
• Signon: Signon: doGet: Entered. • Signon: Signon: genMenu: Entered. The SignOn doGet method is called twice. The first time it is called with a parameter named cmd, which is set equal to menu. This causes the genMenu method to be called to generate the application menu. The HTML tags generated by the genMenu method are shown in Figure 219 on page 240.
AS400ABC
- Database query
- Manage print jobs by user
- Manage print jobs by output queue
- Files
- System performance
- Command line
- Change password
- Sign off
Figure 219. Application Menu HTML
240 Building AS/400 Internet-Based Applications with Java The HTML tags control how the other Java servlets are run. To understand how it works, look at the tag for the Database query option: Database query
HTML stands for hypertext markup language. Links are the hyper part of hypertext. Links, which are also called anchors, mark text or images as elements that point to other documents, images, applets, or, in this case, servlets. Links are made up of three elements: • An anchor tag , which marks the text or image as a link • An attribute, HREF=" ", which is located within the opening anchor tag • An address (URL), which tells the browser what to link to, http://AS400ABC:1040/servlet/DbSelectServlet
In this case, clicking on the text DataBase query links us to the servlet named DbSelectServlet: • Signon: Signon: doGet: Entered. • Signon: Signon: genInfo: Entered.
Finally the doGet method is called again with a parameter of info. The genInfo method is called to generate the right portion of the application menu. The window shown in Figure 220 appears.
Figure 220. Application Menu
Developing AS/400 Java Servlets 241 7.3 The Java Application Programs Now that you understand how the servlets are invoked, you can look at how they work. The application servlets are similar. This section looks at a fairly simple servlet, which calls a program on the AS/400 system and a more complex application which allows SQL query statements to be created and executed on the AS/400 system. By understanding how these applications work, you can look at the code and understand how the other applications work.
7.3.1 System Performance Servlet This section looks at the System performance servlet. This servlet uses the AS/400 Toolbox for Java distributed program call (DPC) class to call a program on the AS/400 system, which returns system performance information. The information returned by the AS/400 program is displayed in the browser by imbedding it in an HTML file.
public void doGet (HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException { AS400 sys = null; imgBase = "http://" + req.getServerName() + ":" + Integer.toString(req.getServerPort()) + "/"; String sysName = req.getParameter("system"); String userId = req.getParameter("user"); ServletCallLog.logCaller(req, res);
ServletOutputStream out = res.getOutputStream();
// set content type and other response header fields first res.setContentType("text/html");
String realSystem = sysName.toUpperCase(); if (sysName.equalsIgnoreCase("localhost")) { String earl = HttpUtils.getRequestURL(req).toString(); realSystem = getHostFromURL(earl); } // then write the data of the response System.out.println("PerfMon: doGet: Starting output"); out.println("
Performance Information for " + realSystem + "
"); out.println("");
try { sys = getSysFromUserCache(req, res, sysName, userId); getStatus(out, sys); } catch (Exception e) { out.println(e.toString()); e.printStackTrace(); }
out.println(""); out.close(); sys.disconnectService(AS400.COMMAND); }
Figure 221. The PerfMon Class doGet Method
242 Building AS/400 Internet-Based Applications with Java Clicking on the System Performance option invokes the doGet method of the PerfMon class, which is shown in Figure 221 on page 242, of the PerfMon servlet. This method builds the HTML tags for the display headings. It then calls the getStatus method.
The getStatus method performs the following actions: 1. Creates a ProgramCall object named pgm. 2. Creates the parameters for the pgm object. 3. Sets the name of the AS/400 program to call equal to QSYS.LIB/QWCRSSTS.PGM. 4. Calls the AS/400 program. 5. Formats the returned values into HTML tags for: – CPU utilization – DASD utilization – Total Jobs – Total DASD
Figure 222. System Performance Information
7.3.2 Database Query The Database Query application is the most complex of the applications. It is actually made up of a combination of applets and servlets. The following classes make up the DataBase Query application: • DbSelectServlet—Servlet • SQLOrder—Applet • SQLWhere—Applet • SQLWizard—Applet
When you click on the Database query option from the application menu, the doGet method of the DbSelectServlet class is called with a parameter of qrylist. Refer to Figure 219 on page 240, to see the HTML file used. The doGet method checks the parameter to determine which method to call. In this case, the
Developing AS/400 Java Servlets 243 getSavedQueries method is called to allow you to recall previously created queries. This method generates the HTML file shown in Figure 223.
Saved Queries
Enter the SQL statement. For example, 'select * from apilib.parts' to use the demo database.
If you would like some assistance, you can use the wizard button to get some help on formulating your query. SQL gurus can simply type in the query and use the query button.
Figure 225. HTML Generated by the queryPrompt Method
Displaying this HTML file in a browser shows the window that appears in Figure 226 on page 247. The action of this HTML file is to call the DbSelectServlet class using a post method. It sets the following parameters: • name=cmd, value=query • name=system, value=as400abc • name=user, value=auser • name=key, value=as400abcauser908479492129 • radio name=qtype, default=html • name=wizard, value=Wizard • name=save, value=Save...
246 Building AS/400 Internet-Based Applications with Java Figure 226. Query Statement Window
7.3.2.1 Writing your Own SQL Statements At this point in the Database Query application, you can enter your own SQL statements or use the Wizard to help you build an SQL statement. To see how the Wizard works, refer to Section 7.3.2.2, “Using the Wizard” on page 248. In this section, write our own SQL statement: select * from apilib.parts
Clicking on the Query button runs the doPost method. If a cmd value of query is received in the doPost method, the performQuery method is called. The performQuery method sees how we want the results returned by checking which radio button is selected. In this case, the View results in HTML radio button is selected, so the fillTable method is called.
The fillTable method actually causes the sql statement to be executed on the AS/400 system. It does the following: • Creates a connection object using the JDBC DriverManager getConnection method • Creates a statement object using the createStatement method • Execute the SQL statement we entered using the statement object • Formats the rows into a table using HTML tags if a resultset is returned • Causes the browser to execute the HTML file to show the results
The output from the HTML file displayed by the browser is shown in Figure 227 on page 248.
Developing AS/400 Java Servlets 247 Figure 227. Query Results
7.3.2.2 Using the Wizard If the Wizard button is clicked, the wizPrompt method is executed. It builds and shows the HTML file shown in Figure 228 on page 249.
248 Building AS/400 Internet-Based Applications with Java
Enter the Table Name
Table name:
Enter the table name. For example, 'apilib.parts'
Figure 228. HTML File Generated by the wizPrompt Method
The output of this HTML file appears in a browser as shown in Figure 229.
Figure 229. Enter Table Name Prompt
The action of this HTML file is to call the DbSelectServlet class using a post method. It sets the following parameters: • name=cmd, value=qwcolinfo • name=system, value=as400abc • name=user, value=auser
Developing AS/400 Java Servlets 249 • name=key, value=as400abcauser908479492129 • radio name=qtype, default=html • name=wizact, value=Browse... • name=wizact, value=Next... • name=wizact, value=Finish
Clicking on the Next button runs the doPost method with a cmd parameter equal to qwcolinfo. This action, in turn, runs the wizColInfo method. It generates and displays the HTML file shown in Figure 230.
Select Fields
Figure 230. HTML Generated By the wizColInfo Method
This HTML file runs an applet named SqlWizard.
250 Building AS/400 Internet-Based Applications with Java Figure 231. SQLWizard Applet
The SqlWizard applet allows you to select which table columns you want to add to the selection criteria. As shown in Figure 231, we select the PARTNO, PARTQY, and PARTPR columns.
The action of this HTML file is to call the DbSelectServlet class using a post method. It sets the following parameters: • name=cmd, value=qwwhere • name=system, value=as400abc • name=user, value=auser • name=key, value=as400abcauser908479492129 • name=wizact, value=Next... • name=wizact, value=Finish
Click on the Next button to run the doPost method, with the cmd parameter set to qwwhere. Now, the wizWhere method is run. It generates and executes the HTML file shown in Figure 232 on page 252.
Developing AS/400 Java Servlets 251
Select Conditions
Figure 232. HTML File Generated by the wizWhere Method
The HTML file shown in Figure 232 runs an applet named SqlWhere.
252 Building AS/400 Internet-Based Applications with Java Figure 233. SQLWhere Applet
The SQLWhere applet allows you to add a where clause to the SQL statement. In this case, we want only those records that have a PARTQY field value of greater than 50.
The action of this HTML file is to call the DbSelectServlet class using a post method. It sets the following parameters: • name=cmd, value=qworder • name=system, value=as400abc • name=user, value=auser • name=key, value=as400abcauser908479492129 • name=wizact, value=Next... • name=wizact, value=Finish
Clicking on the Next button runs the doPost method, with the cmd parameter set to qworder. Now the wizOrder method runs. It generates and executes the HTML file shown in Figure 234 on page 254.
Developing AS/400 Java Servlets 253
Select Order
Figure 234. HTML File Generated by the wizOrder Method
This HTML file runs an applet named SqlOrder.
Figure 235. SqlOrder Applet
254 Building AS/400 Internet-Based Applications with Java The SqlOrder applet, allows us to add an order by clause to the sql statement. In this case, we want to display the results in ascending order, based on the PARTQY field.
The action of this HTML file is to call the DbSelectServlet class using a post method. It sets the following parameters: • name=cmd, value=qryprompt • name=system, value=as400abc • name=user, value=auser • name=key, value=as400abcauser908479492129 • name=wizact, value=Next... • name=wizact, value=Finish
Clicking on the Finish button starts the doPost method, with the cmd parameter set to qryprompt. If a cmd value of qryprompt is received in the doPost method, the qryPrompt method is called. The qryPrompt method builds and displays the HTML file shown in Figure 236.
Query AS/400 Database
Query statement:
View results in HTML Comma separated variable (CSV) format Tab separated variable (TSV) format
Enter the SQL statement. For example, 'select * from apilib.parts' to use the demo database.
If you would like some assistance, you can use the wizard button to get some help on formulating your query. SQL gurus can simply type in the query and use the query button.
Figure 236. HTML File for the queryPrompt Method
Displaying this file in a browser returns you to the Query AS/400 Database window shown in Figure 237 on page 256.
Developing AS/400 Java Servlets 255 Figure 237. Query AS/400 Database
The text area of the Query AS/400 Database window displays the SQL statement that we created.
Clicking on the Query button runs the doPost method. If a cmd value of query is received in the doPost method, the performQuery method is called. The performQuery method verifies how we want the results returned by checking which radio button is selected. In this case, the View results in HTML radio button is selected, so the fillTable method is called.
The fillTable method actually runs the SQL statement on the AS/400 system. It does the following: • Creates a connection object using the JDBC DriverManager getConnection method • Creates a statement object using the createStatement method • Executes the SQL statement we entered using the statement object • Formats the rows into a table using HTML tags if a resultset is returned • Causes the browser to execute the HTML file to display the results
Clicking on the Query button runs the statement. The results are shown in Figure 238 on page 257.
256 Building AS/400 Internet-Based Applications with Java Figure 238. SQL Result
7.4 Running the Application The application discussed in this chapter uses servlets to access AS/400 resources. To run it, we need a server that supports Java servlets. We tested the application using two servers: • Domino Go Webserver and ServletExpress running on a Windows/NT platform • The IBM HTTP Server for AS/400 and the WebSphere Application Server for AS/400 running on an AS/400 system
7.4.1 Domino Go Webserver For details about configuring Domino Go Webserver and ServletExpress, see Section 9.1, “Domino Go Webserver” on page 287. For the application to be served by the Domino Go Webserver, you must: 1. Export the class files to a directory where the Web server can find them. 2. Add the appropriate directives to the Domino Go server request routing table.
By default the Domino Go Webserver serves servlets from following directory: \ServletExpress\servlets
We export the servlet classes to this directory. Figure 239 on page 258 shows the servlet classes exported to the \ServletExpress\servlets directory.
Developing AS/400 Java Servlets 257 Figure 239. ServletExpress\servlets Directory
We also use three applets as part of this application. To keep access to the applets secure and separate from the servlets, we export them to the following directory: \ServletExpress\servlets\applets
Figure 240 shows the content of the \Servlet\Express\applets directory.
Figure 240. Applet Directory
The application uses gif files to display images. The gif files are stored in the apptest directory. Figure 241 shows the content of the apptest directory.
Figure 241. apptest Directory
We add the following directives to the Domino Go server request routing table: • Pass /apptest/* \apptest\* This directive allows us serve the gif files from the apptest directory.
258 Building AS/400 Internet-Based Applications with Java • Pass /applets/* c:\ServletExpress\servlets\applets\* This directive allows us to serve the applets from the applets directory.
7.4.2 IBM HTTP Server for AS/400 We can also serve this application using the IBM HTTP Server for AS/400 and the WebSphere Application Server for AS/400. For configuration details about running under the IBM HTTP Server for AS/400, see Section 9.3, “IBM HTTP Server for AS/400” on page 293.
To allow the application to be served by the IBM HTTP Server for AS/400, you must: 1. Export the class files to a directory where the Web server can find them. 2. Add the appropriate directives to the Domino Go server request routing table.
By default IBM HTTP Server for AS/400 serves servlets from the following directory: \QIBM\ProdData\IBMWebAS\servlets
We export the servlet classes to this directory. Figure 242 shows the servlet classes exported to the \QIBM\ProdData\IBMWebAS\servlets.
Figure 242. \QIBM\ProdData\IBMWebAS\servlets Directory
We also use three applets as part of this application. To keep access to the applets secure and separate form the servlets, we export them to the following directory: \QIBM\ProdData\IBMWebAS\servlets\applets
Figure 243 on page 260 shows the content of the \Servlet\Express\applets directory.
Developing AS/400 Java Servlets 259 Figure 243. Applet Directory
The application uses gif files to display images. The gif files are stored in the apptest directory. Figure 244 shows the content of the apptest directory.
Figure 244. The apptest Directory
We add the following directives to the IBM HTTP Server for AS/400 request routing table: • Pass /apptest/* /apptest/* This directive allows us serve the gif files from the apptest directory. • Pass /applets/* /QIBM/ProdData/IBMWebAS/servlets/applets This directive allows us to serve the applets from the applets directory.
260 Building AS/400 Internet-Based Applications with Java Chapter 8. Security Considerations
This chapter explains how you can provide security for your Internet application. This chapter describes: • An overview of the elements of transaction security available on the Internet •A high level explanation of the Secure Sockets Layer (SSL) protocol • How to use Digital Certificate Manager on AS/400 to create an intranet Certificate Authority (CA) and server certificates • How to configure the IBM HTTP Server for AS/400 to use SSL • Running a servlet under SSL
8.1 Internet Security Elements There is no one single answer to Internet security. Some people think that by installing a firewall between their networks and the Internet the company’s network will be safe.
Is it simply a firewall that shields your company from any inappropriate Internet access? No, security is not a single device or procedure. Security is a concept. It is a set of different security measures that are selected based on the needs of a specific installation. Therefore, it is essential to discuss first the type of Internet security you need to achieve. Security is not simply a firewall.
First, the policy established by high-level management indicates how your company wants to deal with the Internet and what level of security is to be achieved. Various Internet security features, such as cryptography or host system security functions, help you to implement what is designed.
Users must be educated to follow and maintain the implemented security procedures, as well as to observe specific rules when acting as Internet clients. These concepts are highlighted in Figure 245 on page 262.
© Copyright IBM Corp. 1999 261
Internet
Internet
Figure 245. Internet Security Elements
8.1.1 Transaction Security and Secure Sockets Layer Transaction security includes several basic elements, such as: • Confidentiality and privacy •Integrity • Authentication • Accountability
Web server
Web browser
Client identity authenticated Server identity authenticated
Figure 246. Transaction Security
SSL is the Secure Sockets Layer protocol defined by Netscape Communications Corporation. It provides a private channel between client and server that ensures privacy of data, authentication of session partners, and message integrity.
262 Building AS/400 Internet-Based Applications with Java Digital certificates are used for session partner authentication. Server authentication is common. Client authentication is not yet common, but it is growing in popularity. Keys are the base for end-to-end information encryption. Figure 246 provides a high level view of SSL and transaction security.
TCP/IP applications must be rewritten to use SSL. Primarily SSL is used by HTTP (HTTPS) for Web browsing. In OS/400, the V4R3 Directory Services Server (LDAP) is SSL enabled. Other TCP/IP applications will follow.
8.1.1.1 Confidentiality Consider this problem: Intruders can eavesdrop on private information as messages travel across the network. The solution lies in encryption. The sender scrambles the message, and the receiver unscrambles it using a secret key.
Confidentiality means that the contents of the messages remain private as they pass through the Internet. Without confidentiality, your computer broadcasts the message to the network, which is similar to shouting the information across a crowded room. Encryption ensures confidentiality.
8.1.1.2 Integrity Consider, for example, that you want to know if the data received is the same as the data that was sent. You can determine this through two possible solutions: digital signature (hashing) and encryption.
The sending system calculates a value based on the data that is sent. The value is appended to the transmission. The receiving system uses the same calculation to generate a value. The receiving system compares the calculated value with the received value. If the values are different, it assumes that the data changed. Message hashing should be used with encryption for better protection.
Integrity means that the messages are not altered while being transmitted. Any router along the way can insert or delete text or garble the message as it passes by. Without integrity, you have no guarantee that the message you sent matches the message received. Encryption and digital signature ensure integrity.
8.1.1.3 Authenticity Consider the scenario where you want to know who is at the other end of a Web site to test its authenticity. One way to find out is through the use of digital certificates and digital signatures (see Figure 247 on page 264).
Security Considerations 263 Authenticity Problem - How do we know who is at the other end?
This site does not have a I am going to setup a fake site to Certificate from a trusted source. I sell football tickets. No one will think I'll order some football tickets ever know. I'll make millions. from someone else.
Certificate University of the Internet
Issue Date Distinguished Name Public Key Expiration Date Digital Signature of CA
Figure 247. Verifying Identity—Digital Certificates and Digital Signatures
Authenticity means that you know who you are talking to and that you trust that person. Without authenticity, you have no way to be sure that anyone is who they say they are. Authentication through digital certificates and digital signatures ensure authenticity.
There are two ways in which the server uses authentication: •Digital signature •Digital certificates
A digital signature ensures accountability. But how do you know if the person sending you a message is who he says he is?
You look at the sender's digital certificate. A public key certificate is issued by a trusted third party known as the certifying authority (CA). The browser and server exchange information including their public key certificate. SSL uses the information to identify and authenticate the sender of the certificate.
A digital certificate is like a credit card with your picture on it and a picture of the bank president with his arm around you. A merchant trusts you more because you look like the picture on the credit card, and they know the bank president trusts you, too.
You base your trust for the authenticity of the sender on whether you trust the third party (a person or agency) that certified the sender. The third party or certification authority (CA) issues digital certificates.
How can you ensure that the person sending the message is really trustworthy? Consider the following an example, which illustrates this point.
If you wake up one day feeling ill, you may decide to visit a doctor. You can select a doctor from your phone book and go to his or her office for a visit. Once you arrive at the office, how can you be sure that the person about to examine you is really a doctor? After all, you have never met this person before. They may look like a doctor and act like a doctor, but how do you know that this person has successfully completed all the training necessary to become a doctor?
264 Building AS/400 Internet-Based Applications with Java You need certification by a trusted third party to reassure you that this person really is a doctor. The doctor probably has a diploma on the wall stating that they have successfully completed their training. If the diploma is from a well-known school, you would probably be reassured that you are about to be examined by a real doctor. What if the diploma is from the medical school of a correspondence school whose name you don't recognize? You may not be reassured.
Authentication works the same way. Trusted third parties verify that the server really is who it claims to be. This verification is provided with a digital certificate (the digital equivalent of your doctor's diploma hanging on the wall). You base your trust for the authenticity of the server on whether you trust the third party that certified the server (the school that issued the diploma). That third party is called a Certifying Authority (CA).
The term trusted root is given to a trusted certifying authority (CA) on your server. A trusted root key is the key belonging to the CA.
Authentication can be used server to client (server authentication) or client to server (client authentication). Server authentication is described earlier. The clients authenticate the servers. With client authentication, the client is authenticated by the server. For example, if a server contains hospital patient information, we may use client authentication to verify that the client attempting to access the data is really who he said he is before allowing him access to patient records.
8.1.1.4 Accountability Consider the situation where you want to prove that a transaction took place. We combine all the techniques we have seen. First the data is hashed using cryptography to assure its integrity. The data is encrypted using the keys derived from the public key exchange, which assures the identity of the session partners. This is used in combination with a time stamp in the data to provide a log of the transactions.
Accountability means that both sender and receiver agree that the exchange took place. Without accountability, the addressee can easily say that the message never arrived. Digital signatures ensure accountability. Accountability is not part of the SSL protocol.
8.1.2 HTTP Server Over SSL (HTTPS) SSL ensures that data transferred between a client and a server remains private. It allows the client to authenticate the identity of the server. In addition, SSL V3 allows a server to authenticate a client.
Figure 248 on page 266 shows the high level view of the flow that takes place when a client (browser) sends an https request to an HTTP server.
Security Considerations 265 Browser sends HTTPS:// request 1.The user needs to send 2.The server retrieves a private data (for example, certificate from an credit card number). authority that the browser 3.The certificate signature Server certificate sent back recognizes. is checked by the browser. 4.The browser confirms The information is sent to the server that the server is the 5.The server un-encrypts encrypted with negotiated session key the data with negotiated desired one and encrypts session key. the data.
Figure 248. HTTP Server Using SSL
If SSL client authentication is configured, the server requests the client’s certificate for any https request. The server establishes a secure session depending on whether the client has a valid certificate. This depends on the server configuration: no client authentication, optional client authentication, and mandatory client authentication.
Once your server has a digital certificate, SSL enabled browsers can communicate securely with your server using SSL. With SSL, you can easily establish a security-enabled Web site on the Internet or on your corporate network.
SSL uses a security handshake to initiate the secure TCP/IP connection between the client and the server. During the handshake, the client and server agree on the security keys that they will use for the session and the algorithms they will use for encryption and to compute message digest or hashes. The client authenticates the server. In addition, if the client requests a document protected by SSL client authentication, the server requests the client’s certificate. After the handshake, SSL is used to encrypt and decrypt all information on both the https requests and the server response, including: • The URL the client is requesting • The contents of any form being submitted • Access authorization information like user names and passwords • All data sent between the client and the server
The benefits of HTTP using SSL include: •Target server is verified for authenticity • Information is encrypted for privacy • Data is checked for transmission integrity
HTTPS is a unique protocol that combines SSL and HTTP. You need to specify https:// as an anchor in HTML documents that link to SSL, protected documents. A client user can open a URL by specifying https:// to request an SSL, protected documents.
Because HTTPS (HTTP + SSL) and HTTP are different protocols and usually use different ports (443 and 80, respectively), you can run both secure and
266 Building AS/400 Internet-Based Applications with Java non-secure servers at the same time. As a result, you can choose to provide information to all users using no security, and specific information only to browsers who make secure requests. This is how a retail company on the Internet can allow users to look through merchandise without security, complete order forms, and send their credit card numbers using SSL security. A browser that does not have support for HTTP over SSL naturally cannot request URLs using HTTPS. The non-SSL browsers do not allow users to send forms that need to be submitted securely.
Figure 249 shows how clients can access the same server instance in normal mode (port 80) or encrypted using SSL (port 443).
OS/400
IBM HTTP Server for AS/400
IBM HTTP Server for AS/400 SSL Non-secure Sockets Secure Port 80 Port 443
http://... https://...
Figure 249. Accessing a Secure HTTP Session
8.2 Digital Certificates and Certificate Authority A digital certificate identifies a user or a system and is required before SSL can be used. Once a server has a digital certificate, SSL-enabled browsers, such as the Netscape Navigator, can communicate securely with the server using SSL. A digital certificate consists of: • Owner’s distinguished name • Owner’s public key •Digital signature of certificate authority (CA) • Name of the CA • Issue date of certificate • Certificate expiration date • Serial number
Plus, digital certificates have the following characteristics: •Digital certificates are digital documents that validate the identity of a certificate's owner. • There are three types of digital certificates: CA, server, and client certificates.
Security Considerations 267 •Digital certificates contain public key—binds it to an identity. •Digital certificates are created by trusted third parties called Certificate Authorities (CA). •Digital certificates can be distributed freely. •Digital signature in the digital certificate prevents tampering.
A digital certificate is issued by a certificate authority (CA). CAs are entities that are trusted to properly issue certificates and have controls in place to prevent fraudulent use. They are the equivalent to the Department of Motor Vehicles for a driver's license. An individual may have many certificates from different CAs just as we have many forms of personal identification (Social Security card, Blue Cross/Blue Shield card, gym membership card.) If we can trust a CA, we can be reasonably assured that any certificate they issue properly represents the individual that is holding it.
The Certificate Authority charges a fee for issuing a certificate. • Certificate Authorities broadcast their public key and Distinguished Name. • People add them as trusted root key to web servers and browsers. • This means your server will trust anyone who has a certificate from that CA. • There are several common CA's in the marketplace. • Servers and browsers are shipped with several default trusted root keys and more can be added as needed.
Some examples of universally recognized Internet Certificate Authorities (CA) include: • Thawte •VeriSign • US Postal Service •AT&T •MCI
For testing purposes or for applications that will be used exclusively in an intranet environment, you may issue digital certificates using an intranet Certificate Authority. The AS/400 system with Digital Certificate Manager (DCM) can act as an intranet Certificate Authority.
For secure communications, the receiver must trust the CA that issued the certificate, whether the receiver is a browser or a server. Any time a sender signs a message, the receiver must have the corresponding CA certificate and public key designated as trusted root key.
8.3 AS/400 Implementation of Digital Certificate Management You can configure your AS/400 system as an intranet Certificate Authority. Digital Certificate Manager (DCM) is a Web-browser based administration facility that allows you to create, manage, and use certificates within an enterprise and with partners of an enterprise. You can use DCM to request digital certificates from Internet Certificate Authorities such as VeriSign and Thawte.
DCM allows you to create your own intranet Certificate Authority (CA). You can then use the CA to dynamically issue digital certificates to servers and users (client certificates) on your intranet. When you create a server certificate, DCM automatically generates the private key and public key for the certificate.
268 Building AS/400 Internet-Based Applications with Java You can also use DCM to register and use digital certificates from Verisign or other commercial organizations on your intranet or the Internet.
Digital Certificate Manager is option 34 of OS/400 (5769-SS1 option 34). You must install this option to use DCM. DCM is a link in the AS/400 Tasks page, which runs in the *ADMIN HTTP server instance. Therefore, you must have installed IBM HTTP Server for AS/400 (5769-DG1) and use it to access DCM. In addition, you must install IBM Cryptographic Access Provider licensed program (5769-AC1,or AC2, or AC3) to create certificate keys. These cryptographic products determine the maximum key length permitted for cryptographic algorithms on your AS/400 system. Government export and import regulations determine which version is available in your country. To use all the options available in DCM, you must have *SECOFR and *SECADM authority.
To access the Digital Certificate Manager, click on the hyperlink for Digital Certificate Manager from the AS/400 Tasks Page. When using Digital Certificate Manager, you can click the Help button on any page at any time to access on-line help.
8.3.1 Configuring a Digital Certificate Environment You can use your AS/400 system to configure a digital certificate environment. You can also configure the HTTP server to use digital certificates and run over SSL.
Perform the following series of steps to configure an intranet digital certificate environment using the AS/400 system as a Certificate Authority: 1. Use DCM to create an intranet CA in one or more AS/400 system. 2. Using DCM, the intranet CA issues server certificates that can be used in the local server (same AS/400 system where the CA is configured) or exported to a remote server. 3. For the clients to recognize and trust the server certificates issued by the intranet CA, the CA certificate must be installed in the browsers and designated as a trusted root. 4. If the server requests client certificates for client authentication, the users must request and install client certificates in their browsers. 5. The HTTP server must be configured to enable SSL (SSL On) and specify the key ring file where the server certificate is stored (keyfile). To optionally authenticate client certificates (SSL_ClientAuth client), add PROTECTION/PROTECT directives to protect resources.
8.4 Creating a Self-Signed Certificate This section describes how to create a self-signed certificate using your AS/400 system as an intranet Certificate Authority.
Because self-signed certificates are not recognized by visitor’s browsers as coming from a trusted third party, they should not be used in customer transaction situations over the Internet. Use them only on your test and development systems, and for demonstration purposes. You can also use a self-signed certificate for intranet applications.
Security Considerations 269 To obtain a self-signed certificate, perform the following tasks: 1. Create an intranet Certificate Authority. 2. Create a server certificate with your intranet CA. 3. Configure your HTTP server to use the server certificate.
8.4.1 Creating an Intranet Certificate Authority Digital Certificate Manager (DCM) allows you to create your own intranet CA in your AS/400 system and use it to issue server and client certificates for testing purposes or applications within your organization.
This section outlines the steps you must perform to create a CA on your AS/400 system. You only need to perform this task if the system administrator has not previously created an intranet Certificate Authority and if you want to use your AS/400 system to issue intranet server certificates.
To create an intranet CA in your AS/400 system, follow these steps: 1. Start the HTTP *ADMIN server on your AS/400 system. From the command line, enter the command: STRTCPSVR SERVER(*HTTP) HTTPSVR(*ADMIN) 2. Access the AS/400 Tasks page from your browser by entering the URL: http:// System_name:2001 3. You are prompted to enter user name and password. Sign on with a user that has *SECOFR and *SECADM authority.
The AS/400 Tasks Page appears as shown in Figure 250.
Figure 250. AS/400 Tasks Page
4. Click on Digital Certificate Manager. 5. Click on Certificate Authority (CA). 6. Click on Create a Certificate Authority. Note: If a Certificate Authority (CA) was previously created on your system, the Create a Certificate Authority link does not appears.
270 Building AS/400 Internet-Based Applications with Java 7. Complete the Create a Certificate Authority form as shown in Figure 251. Replace the field values appropriately with your organization’s information.
Figure 251. Create an Intranet Certificate Authority
Click OK. 8. After DCM processes the form, it stores a copy of the CA certificate in the CA default key ring file: /QIBM/USERDATA/ICSS/CERT/CERTAUTH/DEFAULT.KYR
At this point, you can install the CA certificate in your browser so that it recognizes the certificates issued by the intranet CA. DCM displays the page shown in Figure 252.
Figure 252. CA Certificate Created Successfully
Click Receive Certificate if you want to install the CA certificate in your browser now. Or, click OK to proceed to the next setup window, and install the CA certificate in your browser at later time. Notice the default path and file name where the intranet CA key ring file is stored.
Security Considerations 271 9. Complete the CA Policy Data form to set the client certificate policy for your CA. See Figure 253.
Figure 253. Certificate Authority Policy
This is where you define whether your CA can issue and sign client certificates. If the CA can issue client certificates, indicate the length of time for which the certificates will be valid. 10.The policy data for the Certificate Authority was successfully changed message appears. At this point, you can continue to create a server certificate signed by your Certificate Authority. This allows server authentication by clients that use this system as a server.
8.4.2 Creating a Server Certificate with Your Intranet CA Immediately after creating the intranet CA, DCM leads you to create a server certificate.
To use Secure Sockets Layer (SSL) for secure Web serving, your server must have a digital certificate. When you create a server certificate in DCM, the server certificate and keys are stored in the following default directory and file:
/QIBM/USERDATA/ICSS/CERT/SERVER/DEFAULT.KYR
Note: When you create a server certificate, Digital Certificate Manager (DCM) stores a copy of the CA certificate in the server’s key ring and designates it as a trusted root. 1. Complete the Create a Server Certificate form as shown in Figure 254 replacing the field values with your organization information. The options for the key size are determined by the IBM Cryptographic Access Provider (5769-ACx) licensed program installed in your system. This is the key size that is used to generate your public and private keys.
272 Building AS/400 Internet-Based Applications with Java Figure 254. Create a Server Certificate Page
By default, the system inserts the fully qualified name of the AS/400 system into the system name field. Do not change this name. This is the name used to describe your server. You can give the server any name. However, the fully qualified TCP/IP host name is usually used for the server name. Click OK. 2. The Server Certificate Created Successfully page appears (see Figure 255).
Figure 255. Server Certificate Created Successfully Page
From this page, you can select whether the HTTP ADMIN server or the Directory Services server (LDAP) uses this server certificate for SSL connections. Do not select any of these options. 3. Copy the file and path name where the server certificate is stored to the clipboard. It is: /QIBM/USERDATA/ICSS/CERT/SERVER/DEFAULT.KYR Click OK. Click Done.
Security Considerations 273 8.4.2.1 Creating a Server Certificate with an Existing Intranet CA The steps to create a server certificate described in the previous section assume that you are creating the intranet CA for the first time. If your administrator has already created an intranet CA and server certificate, you can use the existing server certificate in your HTTP server configuration.
If you want to create a new server certificate using an existing intranet CA, start by clicking Create a server certificate under Server Certificates in DCM (see Figure 256).
Figure 256. Create a Server Certificate with an Existing Intranet CA
Select Local Certificate Authority and Click OK.
The Create Server Certificate page appears next (see Figure 254 on page 273).
8.4.2.2 Authorizing QTMHHTTP to the Key Ring File You may need to give QTMHHTTP (or the user profile under which your HTTP server runs) authority to the key ring and stash files. The key ring and stash files are created with *PUBLIC authority *EXCLUDE. QTMHHTTP (or the user profile under which the HTTP server runs) must have at least read rights to those files.
Perform the following steps: 1. To authorize QTMHHTTP to the key ring and stash file, enter the command: WRKLNK ’/QIBM/UserData/ICSS/Cert/Server’ 2. Enter 5, Next level, to display the files in the directory. 3. Enter 9, Work with authority, by the key ring file (DEFAULT.KYR). 4. Enter 1, Add user, User=QTMHHTTP, Data Authority=*R. 5. Repeat steps 1 through 3 to authorize QTMHHTTP to the stash file (DEFAULT.sth).
274 Building AS/400 Internet-Based Applications with Java 8.4.3 Configuring the Web Server to Use SSL with Server Authentication The Web server must be configured to run over SSL and use the server certificate you created in Section 8.4.2, “Creating a Server Certificate with Your Intranet CA” on page 272. To configure your HTTP server to run over SSL and use a server certificate, you must perform the following tasks: 1. From Digital Certificate Manager, click on Return to AS/400 Tasks. The AS/400 Tasks page is displayed (see Figure 250 on page 270). 2. Click on IBM HTTP Server for AS/400. 3. Click on Configuration and Administration. 4. Click on Configurations in the left frame. 5. Select your HTTP configuration file in the drop-down box immediately beneath the Configurations link as shown in Figure 257.
Figure 257. HTTP Server Configuration
6. Click on Security configuration. Fill in the Security configuration page (see Figure 258 on page 276). a. Check Allow SSL connections. b. Accept the default SSL port (443) or specified the port you wish to use for SSL. c. Deselect Enable SSL client authentication. d. Add the key ring path and file name. If you copied it to the clipboard, you can paste it now: /QIBM/USERDATA/ICSS/CERT/SERVER/DEFAULT.KYR
Security Considerations 275 Figure 258. Security Configuration Page
Click Apply. You should see this message at the top of the screen: The configuration file was successfully updated. Server instances that are using this configuration must be stopped and started for the changes to take affect. You should also see your key ring file added in the Key rings box. 7. You should now stop the server instance and start it again. In the left pane window, click Server Instances. 8. Click on Work with server instances. 9. From the drop-down box, select your server instance (see Figure 259).
276 Building AS/400 Internet-Based Applications with Java Figure 259. Work with Server Instances
Click Stop. Wait until you see this message at the top of your window: The server instance was successfully stopped. 10.From the drop-down box, select your server instance (see Figure 259). Click Start. You should see this message: The server instance was successfully started.
You have now successfully configured your Web server to use SSL with server authentication.
8.5 Requesting a Server Certificate from an Internet CA To conduct commercial business on the Internet, you should request your server certificate from an Internet Certificate Authority, such as VeriSign or Thawte, which are widely known by clients browsers and servers.
For your private Web network within your own company, university, or group, or for testing purposes you can, using Digital Certificate Manager (DCM), act as your own CA. Section 8.4, “Creating a Self-Signed Certificate” on page 269, explains this procedure.
This section describes how to obtain a server certificate from an Internet certificate authority. To use a server certificate issued by an Internet CA, perform these steps: 1. Request the server certificate from an Internet CA. 2. Receive a server certificate for this server. 3. Configure the HTTP server to use SSL and Server Authentication.
Security Considerations 277 8.5.1 Requesting a Server Certificate from an Internet CA To use SSL for secure Web serving, your server must have a digital certificate. You can use an intranet certification authority (CA) to issue a server certificate (see Section 8.4, “Creating a Self-Signed Certificate” on page 269), or you can use an Internet CA.
When you choose to use an Internet CA to issue a server certificate, you must first request the certificate. Follow these steps: 1. From the Digital Certificate Manager (DCM) page, click Server Certificates in the left-hand frame to display an extended list of server tasks. 2. Click on Create a server certificate from the list to display the Select a Certificate Authority page. 3. Select VeriSign or other Internet Certificate Authority as shown in Figure 260.
Figure 260. Requesting a Certificate from VeriSign or other Internet Certificate Authority
Click OK to display the Create a Server Certificate form. 4. Complete the Create a Server Certificate form as show in Figure 261 on page 279 replacing the field values with your organization information. The options for the key size are determined by the IBM Cryptographic Access Provider (5769-ACx) licensed program installed in your system. This is the key size that will be used to generate your public and private keys.
278 Building AS/400 Internet-Based Applications with Java Figure 261. Request a Server Certificate from an Internet CA
By default, the system inserts the fully qualified name of the AS/400 system into the system name field. Do not change this name. This is the name used to describe your server. You can give the server any name, although the fully qualified TCP/IP host name is usually used for the server name. Click OK to process the Create a Certificate Request form. You receive the Server Certificate Request Created page as shown in Figure 262.
Figure 262. Server Certificate Request Generated by DCM
Note: Do not click done or close the browser yet. You need to cut and paste the certificate request when you submit the Certificate Signing Request to the Internet CA. 5. Copy the Server Certificate Request to your clipboard. Start at -----BEGIN NEW CERTIFICATE REQUEST----- and end at -----END NEW CERTIFICATE REQUEST-----. Click Done to close the page.
Security Considerations 279 6. Follow your Internet CA procedures to paste the certificate request. For example, to request a certificate from VeriSign, follow the instructions that are described on the following URL: http://www.verisign.com When VeriSign is satisfied that you meet all of its requirements, it e-mails the secure server certificate to you. You should receive it in three to five business days. Other certificates authorities have their own procedures.
8.5.2 Receiving a Server Certificate for this Server After you receive the certificate from the Internet CA, you need to copy the signed server certificate to a text file that DCM can access when you perform the Receive server certificate task. Perform the following steps: 1. Copy the signed server certificate presented to you by the Internet CA to your clipboard. Start at -----BEGIN CERTIFICATE REQUEST-----, and end at -----END CERTIFICATE REQUEST-----. 2. Paste the signed server certificate in your clipboard into a .txt file. Use a text editor of your choice, for example Notepad, to create a .txt file and paste the server certificate issued by the Internet CA. 3. Save the file in your AS/400 system IFS. Use a mapped network drive and save the .txt file that contains the server certificate issued by the Internet CA in the following path (enter a file name of your choice): /QIBM/USERDATA/ICSS/CERT/SERVER/rcvcert.txt 4. In DCM, click Receive a server certificate and complete the Receive a Server Certificate page (Figure 263).
Figure 263. Receiving a Server Certificate Issued by an Internet CA
5. The Certificate Received page is displayed. You have the option to use the received certificate with the ADMIN or LDAP server. Do not select these options. Click OK. 6. You should receive a Server Configuration Status message indicating the server certificate operations are complete. Click Done. 7. You must now set the key as the default key. In DCM, click Key management. Complete the Key Management page and select Work with keys (see Figure 264 on page 281).
280 Building AS/400 Internet-Based Applications with Java Figure 264. Key Management Page
8. Select the key with the label corresponding to the certificate you received from the Internet CA (VeriSign_Cert in our example). Select Set key to be the default and click OK.
8.5.3 Configuring the HTTP Server to Use SSL This task is described in Section 8.4.3, “Configuring the Web Server to Use SSL with Server Authentication” on page 275.
8.6 Applying Security to the Applications In this section, we run an application using digital certificates and SSL. Since we are using the security support provided by the IBM HTTP Server for AS/400, the benefits apply directly to servlets. For applets, we can use the HTTP server to initiate the applet, but once the applet starts and is communicating with the AS/400 system, it uses its own sockets connection to interface with the AS/400 system. In this case, you have to provide your own encryption to protect information going across an Internet connection. As discussed in Chapter 3, “Introduction to AS/400 Applets” on page 51, you can use the browser’s security classes to provide digital certificate support.
8.6.1 Servlets In Section 8.3, “AS/400 Implementation of Digital Certificate Management” on page 268, we show configuring the test AS/400 system. We use this configuration to run the servlet discussed in Chapter 4, “Introduction to AS/400 Servlets” on page 159, using Netscape Communicator. If you run the application under another browser, you use similar dialogs to help you control the security of the application. To start the servlet, we enter: https://AS400ABC/apptest/Parts.html
Before the servlet starts, we are presented with security dialogs. Since we did not obtain a digital certificate from a universally recognized Internet Certificate Authority, the browser displays the warning dialog shown in Figure 265 on page 282.
Security Considerations 281 Figure 265. New Site Certificate
Clicking on the Next button causes the dialog shown in Figure 266 to appear. This dialog allows us to display more information about the certificate that is being presented.
Figure 266. New Site Certificate Information
Clicking on the More Info... button shows a dialog which contains information about the issuer of the certificate.
282 Building AS/400 Internet-Based Applications with Java Figure 267. View a Certificate
Clicking on the Next button in the dialog displayed in Figure 266 on page 282, causes the dialog shown in Figure 268 to appear.
Figure 268. New Site Certificate Acceptance Dialog
The dialog shown in Figure 268 allows us to choose how we want to deal with the certificate received from the remote site. In this case, we recognize that it is a site that we can trust, so we set the Accept this certificate for this session radio button on and click on the Next button. This causes the dialog shown in Figure 269 on page 284 to appear.
Security Considerations 283 Figure 269. Netscape Certificate Warning Dialog
After we accept the certificate, the browser displays a final warning that allows us to choose to be reminded with further warning messages. Clicking on the Next button starts the SSL session with the remote system. If this is the first time that we have requested a secure document, we are presented with the dialog shown in Figure 270.
Figure 270. Netscape Security Information Dialog
We can use the check box shown in Figure 270 to control whether we want to see this warning dialog in the future. If we click on the Continue button, the servlet application starts as shown in Figure 271 on page 285. The lock Icon shown in the lower left corner of the browser indicates that we are running under a SSL session.
284 Building AS/400 Internet-Based Applications with Java SSL Enabled
Figure 271. PartsServlet Running under SSL
8.6.2 Additional Resources For additional information, consult the following resources: • HTTP Server for AS/400 Webmaster's Guide • Securing Your AS/400 from Harm on the Internet, SG24-4929 • http://publib.boulder.ibm.com/pubs/html/as400/ic2924/info/index.htm Click Internet—>Digital certificate management • http://www.software.ibm.com/webservers/ • http://www.ibm.com/security • http://www.ics.raleigh.com • http://www.internet.ibm.com/commercepoint/registry/ • http://www.verisign.com/products/doc.html • http://home.netscape.com/assist/security/ssl/index.html • http://www.rsa.com
Security Considerations 285 286 Building AS/400 Internet-Based Applications with Java Chapter 9. HTTP Server Configuration
This chapter shows the HTTP server configurations that we use for this redbook. The chapter explains: • Domino Go Webserver • ServletExpress • IBM HTTP Server for AS/400 • IBM WebSphere Application Server for AS/400
9.1 Domino Go Webserver For more information about Domino Go Webserver, see the Web site: http://www.software.ibm.com/webservers/dgw.
Figure 272. Domino Go Webserver Initial Screen
To see the initial Domino Go Webserver screen, enter the following URL in the browser Location field: http://server:0080
If you are physically on the server system, you can replace the server name with localhost. Perform the following steps: 1. Select CONFIGURATION AND ADMINISTRATION FORMS. 2. You are prompted for security information. The default user ID and password are both admin.
© Copyright IBM Corp. 1999 287 Figure 273. Configuration and Administration Window
3. On the Configuration and Administration Form Screen, select Request Routing.
288 Building AS/400 Internet-Based Applications with Java Figure 274. Domino Go Routing Table
Figure 274 shows the Domino Go Webserver routing table used for this redbook. The entries added were: • Pass /apptest/* \apptest\* This directive allows us serve the gif files from the apptest directory • Pass /applets/* c:\ServletExpress\servlets\applets\* This directive allows us to serve applets from the applets subdirectory
9.2 ServletExpress ServletExpress allows you manage the servlets running under the control of the Web server. You do not have to use ServletExpress to run servlets under the Domino Go HTTP server if they are stored in the default directory. For the PartsServlet class, it is stored in a package named servlets. When you export it, it is exported to a subdirectory named servlets in the default directory. You need to configure ServletExpress so it can find the PartsServlet class. ServletExpress also makes it easy for you to load and unload servlets without stopping the Web server.
HTTP Server Configuration 289 We also use ServletExpress to configure the classpath environment variable that we use. In this case, we use ServletExpress to add the AS/400 Toolbox for Java to the classpath variable.
Start your Web browser, perform the following steps: 1. Enter http://server:9090/ for the URL. 2. Make sure you add :9090 after the server name since the administration tool server listens to the port 9090.
Note If you are physically on the server, you can replace the server name with localhost.
3. Login with the administrator user ID and password (the default is admin/admin). You should see a window similar to the one shown in Figure 275.
Figure 275. ServletExpress Services Dialog
4. Click on the Manage button.
290 Building AS/400 Internet-Based Applications with Java Figure 276. ServletExpress Setup Window
5. In the Setup Window, use the Basic menu option to set the Classpath environment variable. Use the system Classpath or set your own. Be sure that the directory where the AS/400 Toolbox for Java zip file is stored is included in the Classpath. 6. After setting how the Classpath is resolved, select the Servlets button from the toolbar. A window appears as shown in Figure 277 on page 292.
HTTP Server Configuration 291 Figure 277. ServletExpress Add Servlet Dialog
7. You can use this window to add any new servlets. For example, to add the PartsServlet, complete these tasks: a. Select the Add Servlet options from the Servlets tree and add the information: Specify PartsServlet in the Servlet Name: text field b. Specify servlets.PartsServlet in the Servlet Class: text field. Note: Do not add the .class extension c. Press the Add button 8. In the next window that appears, you can see that there are options or buttons to load or unload servlets without the need for shutting down the whole HTTP server.
292 Building AS/400 Internet-Based Applications with Java Figure 278. ServletExpress Servlet Configuration Dialog
9.3 IBM HTTP Server for AS/400 For more information about the IBM HTTP Server for AS/400, see the Web site: http://www.as400.ibm.com/http
We store the class files, jar files, gif files, and HTML files used to run the applets and servlets discussed in this redbook in an Integrated File System (IFS) directory named apptest.
By default, IBM HTTP Server for AS/400 serves servlets from the following directory: /QIBM/ProdData/IBMWebAS/servlets
We also use three applets as part of the servlet discussed in Chapter 7, “Developing AS/400 Java Servlets” on page 221. To keep access to the applets secure and separate from the servlets, we export them to the following directory: /QIBM/ProdData/IBMWebAS/servlets/applets
To run the applets and servlets discussed in this redbook, you need to configure the HTTP Server for AS/400 so it can serve the servlets and applets from these directories.
HTTP Server Configuration 293 Note It is beyond the scope of this redbook to describe in detail how to use the configuration programs for the HTTP Server for AS/400. You can find additional information about how to configure and work the HTTP Server for AS/400 in the following manuals: • HTTP Server for AS/400 Quick Beginnings, GC41-5433 • HTTP Server Webmaster’s Guide, GC41-5434
The configuration task requires that you add directives to the HTTP Server configuration file for the server configuration that will be used for applet and servlet serving. The directives to be added are PASS directives: PASS /apptest/* PASS /applets/* /QIBM/ProdData/IBMWebAS/servlets/applets
If you want to run servlets on the AS/400 system, you must also add special directives to the HTTP configuration, see Section 9.4, “IBM WebSphere Application Server for AS/400” on page 296, for details.
There are two techniques that you can use to add the directives to the server configuration file: • Use the browser-based configuration program. You start this program by entering one of the following URLs in your browser (substitute your server name or IP address in the URL): – http://server_name:2001 – http://ip_address:2001 Figure 279 on page 295 shows the V4R3 version of the browser-based configuration program. You need to navigate to the Configurations-->Request Processing-->Request Routing section of the configuration program to arrive at the page where you can enter the PASS directive. • Use the OS/400 command Work with HTTP Configuration (WRKHTTPCFG). This command is used in a 5250 session to invoke a line editor that can be used to add the PASS directive to a selected configuration file member.
294 Building AS/400 Internet-Based Applications with Java Figure 279. Browser-based HTTP Server Configuration Program
Note Regardless of the technique you use to add the PASS directive to the HTTP Server configuration file, be sure that you place the PASS directive for the apptest directory before the PASS / directive.
The PASS / directive is considered to be a "catch-all" directive. If that directive is encountered before your PASS directive, the HTTP Server attempts to serve the requested HTML file from the directory associated with the PASS / directive.
Start or Restart the HTTP Server Configuration Instance After adding your PASS directive to the HTTP Server configuration file, you need to start or restart the HTTP Server configuration instance.
If the HTTP Server instance is not active, use the following OS/400 command to start the server instance: STRTCPSVR SERVER(*HTTP) HTTPSVR(DEFAULT)
If the HTTP Server instance is already active, use the following OS/400 command to restart the server instance: STRTCPSVR SERVER(*HTTP) RESTART(*HTTP) HTTPSVR(DEFAULT)
For either of those commands, substitute your server instance name if you need to start or restart a server instance other than DEFAULT. For example, we use the name JAVAS for our configuration file.
HTTP Server Configuration 295 9.4 IBM WebSphere Application Server for AS/400 The IBM WebSphere Application Server for AS/400 provides the same functionality of what the product provides on the other shipped platforms. On the AS/400 system, it enables servlet support. Please refer to the official WebSphere Web site for complete product information. It can be found at: http://www.software.ibm.com/webservers/appserv/index.html
Attention A number of PTFs are required to enable the WebSphere support on the AS/400 system. The PTFs are not part of a cumulative tape at this point, so you need to order them. To see the current list of PTFs, go the Web page http://www.as400.ibm.com/http and click on the WebSphere Application Server link.
The AS/400 version has the same installation structure as the other platforms:
In this case, for the AS/400 system,
You can configure a server instance of the IBM HTTP Server for AS/400 to run WebSphere. It is enabled through the Server API of the HTTP Server. Figure 280 shows the configuration directives you need to add to the HTTP server configuration file to enable WebSphere. For the entire listing of the IBM HTTP Server for AS/400 configuration file used for this redbook, refer to Appendix B, “IBM HTTP Server for AS400 Configuration” on page 301.
# Enable WebSphere support Service /servlet/* /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterService* Service /*.jsp /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterService ServerInit /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterInit /QIBM/ProdData/IBMWebAS/properties/server/servlet/servletservice/jvm.properties ServerTerm /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterExit Pass /IBMWebAS/samples/* /QIBM/ProdData/IBMWebAS/samples/* Pass /IBMWebAS/doc/* /QIBM/ProdData/IBMWebAS/doc/* Pass /IBMWebAS/system/admin/* /QIBM/ProdData/IBMWebAS/system/admin/* Pass /IBMWebAS/* /QIBM/ProdData/IBMWebAS/web/* # end - WebSphere support
Figure 280. HTTP Server Directives to Enable WebSphere
In the near future, you can use the Administration and Configuration form of the HTTP Server to add those directives automatically when you select to enable the Java Servlet support.
Note: Today, the form is there, but the directives added are not correct for the WebSphere support.
Once you select the configuration file and add the directives shown in Figure 280 to enable WebSphere, you need to change the jvm.properties files under the /QIBM/ProdData/IBMWebAS/properties/server/servlet/servletservice/ directory. Change the following line in the file to point to your configuration file,
296 Building AS/400 Internet-Based Applications with Java the shipped default is CONFIG. In this case, we use a configuration file named JAVAS.
# Properties for Domino Go #ncf.native.httpd.cnf.path=c:\winnt\httpd.cnf ncf.native.httpd.cnf.path=/QSYS.LIB/QUSRSYS.LIB/QATMHTTPC.FILE/JAVAS.MBR
Figure 281. JVM Properties File
Once you change this line, you are ready to start the IBM WebSphere Application Server on the AS/400 system. Start the HTTP server instance that points to the configuration file that you have configured for WebSphere.
Note It may take a little longer than you expect for your HTTP server instance to come up due to the fact that it needs to create a Java Virtual Machine for WebSphere to run under. Watch the server instance on WRKACTJOB until you see it finish bring coming up and going into TIMW status.
9.4.0.1 Verifying the Installation To verify that you have WebSphere set up correctly, try to run the HelloWorldServlet as your first servlet on the AS/400 system. Set the URL on your browser to: http://yourAS400Server:xxxx/servlet/HelloWorldServlet
yourServer:xxxx is your server name and the corresponding port number you used for this server.
If you "Hello World" appears as the result, your WebSphere Application Server is set up and ready. Again, you need to be patient here to allow the servlet to be loaded into the Java Virtual Machine.
9.4.0.2 WebSphere Administration Graphical User Interface The IBM WebSphere Application Server also provides its own Web-based GUI for configuration, called the Application Server Manager. To get to the GUI, point your browser to the following URL: http://yourAS400Server:9090
The WebSphere Signon window appears as shown in Figure 282 on page 298.
HTTP Server Configuration 297 Figure 282. WebSphere Sign On Screen
The graphical user interface provides configuration screens that allow you to configure servlets. The screens and the configuration scenario is the same as for ServletExpress used with the Domino Go Webserver. Please see Section 9.2, “ServletExpress” on page 289 for details about configuring servlets. You do not need to use the Application Server Manager to run servlets on the AS/400 system from the default directory. For the PartsServlet class, it is stored in a package named servlets. When you export it, it is exported to a subdirectory named servlets in the default directory. You need to configure WebSphere so it can find the PartsServlet class. The WebSphere graphical user interface also makes it easy for you to load and unload servlets without stopping the Web server.
We also use the Application Server Manager to configure the classpath environment variable that we use. In this case, we use the Application Server Manager to add the AS/400 Toolbox for Java to the classpath variable.
The Application Server Manager also makes it easy for you to load and unload servlets without starting and stopping the HTTP server.
298 Building AS/400 Internet-Based Applications with Java Appendix A. Example Programs
The Java programs and the AS/400 programs and libraries used in this redbook are available for you to download from the Internet. These examples were developed using VisualAge for Java Version 2.0 Enterprise edition. OS/400 V3R2 or later is required. To run the servlet examples on the AS/400 system, OS/400 V4R3 or later is required. The following VisualAge for Java projects are available: • AdvancedServlet—Advanced servlet example. See Chapter 7, “Developing AS/400 Java Servlets” on page 221. • AppletWorkshop—Advanced applet example. See Chapter 6, “Developing AS/400 Java Applets” on page 193. • ServletExamples—Beginning applets and servlet examples. See Chapter 3, “Introduction to AS/400 Applets” on page 51 and Chapter 4, “Introduction to AS/400 Servlets” on page 159.
Important Information These example programs have not been subjected to any formal testing. They are provided "as is". Use them for reference only. Please refer to Appendix C, “Special Notices” on page 303, for more information.
A.1 Downloading the Files from the Internet Web Site To use these files, you must download them to your personal computer from the Internet Web site. A file named README.TXT is included. It contains instructions for restoring the AS/400 libraries, the VisualAge for Java examples and runtime notes. The URL to access is: www.redbooks.ibm.com
Click on Additional Materials and select the directory SG245337. In the SG245337 directory, click on readme.txt.
A.2 Setting up VisualAge for Java VisualAge for Java, Enterprise Edition, Version 2.0 requires the following software and hardware for development with the IDE: • Windows 95 or Windows NT 4.0 with service pack 3 • TCP/IP communication protocol • Pentium processor or higher recommended • SVGA 800x600 display or higher (1024x768 recommended) • 64 MB RAM minimum (80 MB recommended) • Frames-capable Web browser – Netscape Navigator 4.04 or higher, or – Microsoft Internet Explorer 4.01 or higher • Java Development Kit (JDK) 1.1 for deploying applications or • JDK 1.1.2 for deploying applications using Swing components
The Java support classes described in the following sections are required:
© Copyright IBM Corp. 1999 299 A.2.1 The AS/400 Toolbox for Java Classes The example programs require that the AS/400 Toolbox for Java classes be inside the VisualAge for Java Integrated Development Environment. You must import these classes inside the IDE. Enterprise Edition simplifies this process. After you install VisualAge for Java 2.0 Enterprise edition, the Toolbox classes are available in the repository as part of the IBM Enterprise Toolkit for AS/400 project. If you want to use the Toolbox classes, perform the following steps: 1. From the workbench, click on File—>Quick Start. 2. Click on Features—>Add Feature—>OK. 3. Select IBM Enterprise Toolkit for AS/400—>OK.
This adds the toolbox classes to your workspace. The IBM Enterprise Toolkit for AS400 is listed under All projects.
The alternative is to perform the following steps: 1. Install LPP 5763-JC1 on an AS/400 system. 2. Download the classes to your workstation. 3. Import the classes into the VisualAge for Java IDE.
A.2.2 IBM Enterprise Data Access Libraries The example programs use these supporting classes. To add them, perform these tasks: 1. From the workbench, click on File—>Quick Start. 2. Click on Features—>Add Feature—>OK. 3. Select IBM Enterprise Data Access Libraries—>OK.
A.2.3 Sun JSDK Class Libraries The example programs use these supporting classes. To add them, perform these steps: 1. Select Selected from the Workbench menu. 2. Select Add—>Project from the pulldown menu. 3. Click on the Add projects from the repository radio button. 4. Select the Sun JSDK class libraries project. 5. Click on the Finish button.
A.2.4 Netscape Security The example programs use these supporting classes. To add them: 1. Select Selected from the Workbench menu. 2. Select Add—>Project from the pulldown menu. 3. Click on the Add projects from the repository radio button. 4. Select the Netscape Security project. 5. Click on the Finish button.
300 Building AS/400 Internet-Based Applications with Java Appendix B. IBM HTTP Server for AS400 Configuration
This appendix contains the configuration file used for the IBM HTTP Server for AS/400. The name of the configuration file is JAVAS. It uses port 1040. 00010 # * * * * * * * * * * * * * * * * * * * * * * * * * * * 00020 # IBM HTTP Server for AS/400 00030 # * * * * * * * * * * * * * * * * * * * * * * * * * * * 00200 #------00210 # *** PORT DIRECTIVES *** 00220 # 00230 # The default port for HTTP is 80. If you change this 00240 # use a port number greater than 1024. 00250 # 00260 # 00270 # Syntax: 00280 # Port
© Copyright IBM Corp. 1999 301 302 Building AS/400 Internet-Based Applications with Java Appendix C. Special Notices
This publication is intended to help anyone who want to build AS/400 Internet based applications with Java. The information in this publication is not intended as the specification of any programming interfaces that are provided by VisualAge for Java or the AS/400 Toolbox for Java. See the PUBLICATIONS section of the IBM Programming Announcement for VisualAge for Java and the AS/400 Toolbox for Java for more information about what publications are considered to be product documentation.
References in this publication to IBM products, programs or services do not imply that IBM intends to make these available in all countries in which IBM operates. Any reference to an IBM product, program, or service is not intended to state or imply that only IBM's product, program, or service may be used. Any functionally equivalent program that does not infringe any of IBM's intellectual property rights may be used instead of the IBM product, program or service.
Information in this book was developed in conjunction with use of the equipment specified, and is limited in application to those specific hardware and software products and levels.
IBM may have patents or pending patent applications covering subject matter in this document. The furnishing of this document does not give you any license to these patents. You can send license inquiries, in writing, to the IBM Director of Licensing, IBM Corporation, 500 Columbus Avenue, Thornwood, NY 10594 USA.
Licensees of this program who wish to have information about it for the purpose of enabling: (i) the exchange of information between independently created programs and other programs (including this one) and (ii) the mutual use of the information which has been exchanged, should contact IBM Corporation, Dept. 600A, Mail Drop 1329, Somers, NY 10589 USA.
Such information may be available, subject to appropriate terms and conditions, including in some cases, payment of a fee.
The information contained in this document has not been submitted to any formal IBM test and is distributed AS IS. The information about non-IBM ("vendor") products in this manual has been supplied by the vendor and IBM assumes no responsibility for its accuracy or completeness. The use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer's ability to evaluate and integrate them into the customer's operational environment. While each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will be obtained elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
Any pointers in this publication to external Web sites are provided for convenience only and do not in any manner serve as an endorsement of these Web sites.
Any performance data contained in this document was determined in a controlled environment, and therefore, the results that may be obtained in other operating environments may vary significantly. Users of this document should verify the applicable data for their specific environment.
© Copyright IBM Corp. 1999 303 Reference to PTF numbers that have not been released through the normal distribution process does not imply general availability. The purpose of including these reference numbers is to alert IBM customers to specific information relative to the implementation of the PTF when it becomes available to each customer according to the normal IBM PTF distribution process.
The following terms are trademarks of the International Business Machines Corporation in the United States and/or other countries: AFP IBM AIX OS/390 AS/400 OS/2 Client Access OS/400 DB2 VisualAge 400
The following terms are trademarks of other companies:
C-bus is a trademark of Corollary, Inc.
Java and HotJava are trademarks of Sun Microsystems, Incorporated.
Microsoft, Windows, Windows NT, and the Windows 95 logo are trademarks or registered trademarks of Microsoft Corporation.
PC Direct is a trademark of Ziff Communications Company and is used by IBM Corporation under license.
Pentium, MMX, ProShare, LANDesk, and ActionMedia are trademarks or registered trademarks of Intel Corporation in the U.S. and other countries.
UNIX is a registered trademark in the United States and other countries licensed exclusively through X/Open Company Limited.
Other company, product, and service names may be trademarks or service marks of others.
304 Building AS/400 Internet-Based Applications with Java Appendix D. Related Publications
The publications listed in this section are considered particularly suitable for a more detailed discussion of the topics covered in this redbook.
D.1 International Technical Support Organization Publications For information on ordering these ITSO publications see “How IBM Employees Can Get ITSO Redbooks” on page 307. • Building AS/400 Applications with Java, SG24-2163 • Application Development with VisualAge for Java Enterprise, SG24-5081 • Securing Your AS/400 from Harm on the Internet, SG24-4929
D.2 Redbooks on CD-ROMs Redbooks are also available on CD-ROMs. Order a subscription and receive updates 2-4 times a year at significant savings.
CD-ROM Title Subscription Collection Kit Number Number System/390 Redbooks Collection SBOF-7201 SK2T-2177 Networking and Systems Management Redbooks Collection SBOF-7370 SK2T-6022 Transaction Processing and Data Management Redbook SBOF-7240 SK2T-8038 Lotus Redbooks Collection SBOF-6899 SK2T-8039 Tivoli Redbooks Collection SBOF-6898 SK2T-8044 AS/400 Redbooks Collection SBOF-7270 SK2T-2849 RS/6000 Redbooks Collection (HTML, BkMgr) SBOF-7230 SK2T-8040 RS/6000 Redbooks Collection (PostScript) SBOF-7205 SK2T-8041 RS/6000 Redbooks Collection (PDF Format) SBOF-8700 SK2T-8043 Application Development Redbooks Collection SBOF-7290 SK2T-8037
D.3 Other Publications These publications are also relevant as further information sources: • HTTP Server for AS/400 Quick Beginnings, GC41-5433 • HTTP Server Webmaster’s Guide, GC41-5434 • Java in a Nutshell, ISBN 1-56592-183-6 • Java Developer's Reference, ISBN 1-57521-129-7 • Object Oriented Technology: A Manager's Guide, ISBN 0-201-56358-4
© Copyright IBM Corp. 1999 305 306 Building AS/400 Internet-Based Applications with Java How to Get ITSO Redbooks
This section explains how both customers and IBM employees can find out about ITSO redbooks, CD-ROMs, workshops, and residencies. A form for ordering books and CD-ROMs is also provided.
This information was current at the time of publication, but is continually subject to change. The latest information may be found at http://www.redbooks.ibm.com/.
How IBM Employees Can Get ITSO Redbooks Employees may request ITSO deliverables (redbooks, BookManager BOOKs, and CD-ROMs) and information about redbooks, workshops, and residencies in the following ways: • Redbooks Web Site on the World Wide Web http://w3.itso.ibm.com/ • PUBORDER – to order hardcopies in the United States • Tools Disks To get LIST3820s of redbooks, type one of the following commands: TOOLCAT REDPRINT TOOLS SENDTO EHONE4 TOOLS2 REDPRINT GET SG24xxxx PACKAGE TOOLS SENDTO CANVM2 TOOLS REDPRINT GET SG24xxxx PACKAGE (Canadian users only) To get BookManager BOOKs of redbooks, type the following command: TOOLCAT REDBOOKS To get lists of redbooks, type the following command: TOOLS SENDTO USDIST MKTTOOLS MKTTOOLS GET ITSOCAT TXT To register for information on workshops, residencies, and redbooks, type the following command: TOOLS SENDTO WTSCPOK TOOLS ZDISK GET ITSOREGI 1998 • REDBOOKS Category on INEWS • Online – send orders to: USIB6FPL at IBMMAIL or DKIBMBSH at IBMMAIL
Redpieces For information so current it is still in the process of being written, look at "Redpieces" on the Redbooks Web Site (http://www.redbooks.ibm.com/redpieces.html). Redpieces are redbooks in progress; not all redbooks become redpieces, and sometimes just a few chapters will be published this way. The intent is to get the information out much quicker than the formal publishing process allows.
© Copyright IBM Corp. 1999 307 How Customers Can Get ITSO Redbooks Customers may request ITSO deliverables (redbooks, BookManager BOOKs, and CD-ROMs) and information about redbooks, workshops, and residencies in the following ways: • Online Orders – send orders to: IBMMAIL Internet In United States usib6fpl at ibmmail [email protected] In Canada caibmbkz at ibmmail [email protected] Outside North America dkibmbsh at ibmmail [email protected] • Telephone Orders United States (toll free) 1-800-879-2755 Canada (toll free) 1-800-IBM-4YOU
Outside North America (long distance charges apply) (+45) 4810-1320 - Danish (+45) 4810-1020 - German (+45) 4810-1420 - Dutch (+45) 4810-1620 - Italian (+45) 4810-1540 - English (+45) 4810-1270 - Norwegian (+45) 4810-1670 - Finnish (+45) 4810-1120 - Spanish (+45) 4810-1220 - French (+45) 4810-1170 - Swedish • Mail Orders – send orders to: IBM Publications IBM Publications IBM Direct Services Publications Customer Support 144-4th Avenue, S.W. Sortemosevej 21 P.O. Box 29570 Calgary, Alberta T2P 3N5 DK-3450 Allerød Raleigh, NC 27626-0570 Canada Denmark USA • Fax – send orders to: United States (toll free) 1-800-445-9269 Canada 1-800-267-4455 Outside North America (+45) 48 14 2207 (long distance charge) • 1-800-IBM-4FAX (United States) or (+1) 408 256 5422 (Outside USA) – ask for: Index # 4421 Abstracts of new redbooks Index # 4422 IBM redbooks Index # 4420 Redbooks for last six months • On the World Wide Web Redbooks Web Site http://www.redbooks.ibm.com IBM Direct Publications Catalog http://www.elink.ibmlink.ibm.com/pbl/pbl
Redpieces For information so current it is still in the process of being written, look at "Redpieces" on the Redbooks Web Site (http://www.redbooks.ibm.com/redpieces.html). Redpieces are redbooks in progress; not all redbooks become redpieces, and sometimes just a few chapters will be published this way. The intent is to get the information out much quicker than the formal publishing process allows.
308 Building AS/400 Internet-Based Applications with Java IBM Redbook Order Form
Please send me the following:
Title Order Number Quantity
First name Last name
Company
Address
City Postal code Country
Telephone number Telefax number VAT number
Invoice to customer number
Credit card number
Credit card expiration date Card issued to Signature
We accept American Express, Diners, Eurocard, Master Card, and Visa. Payment by credit card not available in all countries. Signature mandatory for credit card payment.
309 310 Building AS/400 Internet-Based Applications with Java List of Abbreviations
AFP advanced function printing JFC Java Foundation Classes APA all points addressable JIT Just in Time Compiler AWT Abstract Windowing Toolkit JVM Java Virtual Machine CPW Commercial Processing MI Machine Interface Workload OOA Object Oriented Analysis EAB Enterprise Access Builder OOD Object Oriented Design DAX Data Access Builder OOP Object Oriented Programming DDM Distributed Data Management PTF Program Temporary Fix DPC Distributed Program Call RAD Rapid Application FFST First Failure Support Development Technology RMI Remote Method Invocation GUI Graphical User Interface SCS SNA Character Set HTML Hypertext Markup Language SLIC System Licensed Internal IBM International Business Code Machines Corporation SSL secure sockets layer IDE Integrated Development TIMI Technology Independent Environment Machine Interface ITSO International Technical UML Unified Methodology Support Organization Language JAR Java archive URL Universal Resource Locator JDBC Java Database Connectivity VCE Visual Composition Editor JDK Java Development Toolkit WWW World Wide Web
© Copyright IBM Corp. 1999 311 312 Building AS/400 Internet-Based Applications with Java Index Class Path 70, 71 Numerics CLASSPATH 128, 129, 132 5763-JC1 58, 300 Windows 95/98 126 5769-AC1 41, 47, 269 Windows NT 126 5769-AC2 41, 47 CLASSPATH environment variable 125 5769-AC3 41, 47 com.ibm.as400.access.AS400JDBCDriver 58 5769-DG1 41, 269 com.ibm.ivj.eab.dab 58 5769-NC1 41, 47 Common Gateway Interface 1 5769-NCE 41, 47 Company Database 5769-SS1 41, 269 Customer 179 District 179 Item 179 A Order 179 abbreviations 311 Order Line 179 acronyms 311 Stock 179 ActiveX 29, 133, 142 Compute Now button 74 Add projects from the repository 59 confidentiality 263 All Problems tab 58 configure a digital certificate environment 269 APPLET tag 30, 111, 217 CPW databases 193 Applet Viewer 51, 69, 74, 75, 79 cryptographic support 47 applets 1, 6, 28, 51, 221 Customer Table Layout (CSTMR) 189 applet development scenario 193 applet processing 31 how applets are different from Net.Data and CGI pro- D grams 32 dataAccess 62 sample applet 32 DataAccessor interface 80, 89 scripting 29 methods 89 serving applets from the AS/400 system 130 DB2WWW 7 serving the applet from the PC drive 106 DbSelectServlet 243 when to use 34 digital certificate 114, 267 AppletViewer Properties dialog 76 Digital Certificate Manager 41, 47, 261 ARCHIVE 131 Digital Certificate Manager (DCM) 268, 270, 272, 277, ARCHIVE tag 106, 110 278 AS/400 Toolbox for Java 6, 51, 133, 168, 218, 222, 291, Digital certificates 115, 263, 281 300 digital signature 263 ASCII 3 Distributed Data Management (DDM) 80 ASCII to EBCDIC 3 District Table Layout (Dstrct) 189 authenticity 263 doDelete 164 AUTOEXEC.BAT. 126 doDelete() 161 doGet() 161 domain 62 B domino Go Webserver 174, 221, 222, 257, 287 bibliography 305 routing table 289 doPost() 161 C doPut 164 doPut() 161 Cart applet 194 CartApplet class 197 cert2spc 116 E Certificate Authority (CA) 115, 261, 264, 268, 281 EBCDIC 3 CGI 1, 6, 15, 41, 44 EBCDIC to ASCII 5 APIs 17 encryption 263 Processing 16 sample RPG-CGI 20 when to use 28 F why use 15 FORM 31 chkjava 116 forms 2 Choose Bean 65 Choose Bean icon 63
© Copyright IBM Corp. 1999 313 G Netscape Navigator 142 Generate meta data method 68 network access 154 Get method 3 running 137 getParameter() 165 show Java Console 154 getParameterNames() 165 summary 156 getParameterValues 173 Java servlets 1 getParameterValues() 165 JavaScript 29 gif files 258, 260 JDBC 58, 80, 168 properties object 93 JDBCPartsCatalog class 90 H methods 90 HelloWorldServlet 166 jt400.jar 109, 128, 130 HotJava 28 jt400.zip 109, 125, 128, 129, 132 HTML 2, 4, 106, 133, 172 HTTP 3, 42, 164, 270 HTTP 1.1 42, 164 L HTTPS 263, 265 launching the Applet Viewer 74 HttpServletResponse 37 LDAP 280 Hypertext Markup Language 2 Lotus Domino server 5
I M IBM Enterprise Access Libraries 198 makecert 116 IBM Enterprise Data Access Libraries 58, 59, 72, 300 Microsoft Internet Explorer 28, 113, 156, 221 IBM Enterprise Toolkit for AS/400 project 300 signed cabinet file 114 IBM Enterprise Toolkit for AS400 59, 72 Microsoft Java Software Development Kit (SDK) 115 IBM HTTP Server for AS/400 1, 3, 5, 31, 41, 43, 51, 114, 132, 174, 177, 178, 221, 260, 261, 287, 296 N serving applets from 129 Net.Data 1, 6 IBM WebSphere Application Server for AS/400 41, 48, Net.Data macros 9 177, 287 Net.Data Processing 7 Application Server Manager 297 sample Net.Data macro 10 import 52 when to use 14 import dialog 55 Netscape 110, 112 Import SmartGuide 53 enablePrivilege code 112 Integrated PC Server (IPCS) 6 Java console 110 Internet Connection Secure Server (ICSS) 47 security prompt 112 Internet Connection Server (ICS) 41 Netscape Navigator 28, 156, 221 Internet shopping application 193 security 93 CartApplet applet 211, 215 Netscape Security 59, 72 ItemsDb class 200 Netscape Security project 59, 300 SelectedItems class 198 ToolboxApplet" applet 209 Item Table Layout (ITEM) 191 O ItemsDb 197 ODBC 5 ItemsDb class 197 ORDENTR 181 Order Line Table Layout (ORDLIN) 190 Order Status applet 196 J Order Table Layout (ORDERS) 190 JarMaker 157 Java and REXX CGI 44 Java applets 1 P Java Console 110 Part class 96 Java Plug-in 51, 133, 156 methods 97 a step-by-step approach 134 PartsCatalog bean 63 cache JARs in memory 154 PartsCatalog class 100 control panel 154 defaultDataAccessor method 101 enable Java Plug-in 154 methods 100 HTML converter 136 PartsServlet servlet 167 Internet Explorer 140 PartsView applet 51, 61, 112 Java run time parameters 154 running 77
314 Building AS/400 Internet-Based Applications with Java PartsView class 81 init method 163 handleException 87 introduction to the servlet support 160 methods 82 invoking 165 persistent CGI 41, 45 javax.servlet 169 persistent connections 42 javax.servlet.http 169 Plug-in 133 lifecycle 163 Post method 3 parameters 164 Project path field 72 running on the AS/400 system 177 Proxy caching 43 sample servlet 37 Proxy logging 44 service method 163 PRTODERR 181 servlet processing 35 servlets versus CGI 162 three tier implementation 175 Q two tier implementation 177 QOpenSys 43 when to use 39 QTMHHTTP 274 why use 34, 161 QtmhWrStout 20 set Applet attributes 71 QZHBCGI 17 setting AppletViewer properties 75 QzhbCgiParse 18, 44 Setting up VisualAge for Java 299 shopping application 193 R signcode 116 redbook.dat repository 55 signed cabinet file 114, 120 repository 55 creating 114 requesting a server certificate 277 SLTCUSTR 181 resolving problems in the imported applet 57 SLTPARTR 181 RPG application flow 181 SQLOrder 243 RPG order entry application 179 SQLWhere 243 customer transaction flow 181 SQLWizard 243 ORDENTR 181 SSL 267 PRTODERR 181 Configure the Web Server to Use 275 SLTCUSTR 181 Standard Input (STDIN) 3 SLTPARTR 181 Standard Output (STDOUT) 5 tables 189 StatusApplet 197 runnable class 72 StatusApplet class 197 STDIN 27 STDOUT 28, 37 S Stock Table Layout (Stock) 191 Secure Sockets Layer (SSL) 41, 221, 261, 272 STRTCPSVR 295 SelectedItems 197 Sun Java Plug-in 133 SelectedItems class 197, 198 Sun JSDK 169 self-signed certificate 269 class libraries 300 servlet package 169 Sun JSDK class libraries 300 ServletExpress 175, 257, 287 add servlet dialog 292 configure 176, 289 T services dialog 290 TCP/IP 263 servlet configuration dialog 293 TestPart class 94 setting the Classpath 291 methods 95 setup window 291 Thawte 268, 277 ServletRequest 164 Toolbox applet 194 ServletResponse 164 ToolboxApplet class 197 servlets 1, 6, 34, 41, 159, 221 Tools for Internet Development on the AS/400 6 communication with an HTTP server 164 destroy method 163 V developing a servlet application 166 VBScript 29 doGet 164, 170 vector 85, 198 doPost 164, 172 VectorEnumeration 198 HelloWorldServlet 166, 297 VeriSign 268, 277 how to use 163 virtual hosts 42, 43 HTML 172 Visual Composition editor 66
315 VisualAge for Java IDE 52 VisualAge for Java workspace 64
W WebSphere Administration Graphical User Interface 297 WebSphere Application Server 41, 48, 177 WebSphere Application Server for AS/400 177, 257, 259 Application Server Manager 297 what it provides 48 WebSphere Sign On screen 298 WRKHTTPCFG 294
316 Building AS/400 Internet-Based Applications with Java ITSO Redbook Evaluation
Building AS/400 Internet-Based Applications with Java SG24-5337-00
Your feedback is very important to help us maintain the quality of ITSO redbooks. Please complete this questionnaire and return it using one of the following methods: • Use the online evaluation form found at http://www.redbooks.ibm.com • Fax this form to: USA International Access Code + 1 914 432 8264 • Send your comments in an Internet note to [email protected]
Which of the following best describes you? _ Customer _ Business Partner _ Solution Developer _ IBM employee _ None of the above
Please rate your overall satisfaction with this book using the scale: (1 = very good, 2 = good, 3 = average, 4 = poor, 5 = very poor)
Overall Satisfaction ______
Please answer the following questions:
Was this redbook published in time for your needs? Yes___ No___
If no, please explain:
What other redbooks would you like to see published?
Comments/Suggestions: (THANK YOU FOR YOUR FEEDBACK!)
© Copyright IBM Corp. 1999 317 SG24-5337-00 Building AS/400 Applications Internet-Based with Java Printed in the U.S.A. SG24-5337-00